Spring Security 模拟用户登录并授权

@Autowired
private UserDetailsService userDetailsService;

@Autowired
private AuthenticationManager authenticationManager;

public void login(String username, String token) {
    /*
    UserDetails userDetails = org.springframework.security.core.userdetails.User
            .withUsername("user")
            .password("password")
            .passwordEncoder(s -> PasswordEncoderFactories.createDelegatingPasswordEncoder().encode(s))
            .roles("USER")
            .build();
     */
    UserDetails userDetails = userDetailsService.loadUserByUsername(username);
    if (userDetails != null) {
        // 这里可以进行一些其他的用户信息验证,例如验证token是否有效等
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        Authentication authentication = authenticationManager.authenticate(authenticationToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);
    } else {
        // 用户不存在,进行一些其他处理,如创建新用户等
        // do something
    }
}

正常情况下,UserDetails通过UserDetailsService.loadUserByUsername("")获取,上述代码可用于:
1、模拟用户登录
2、接口调试时为用户授权
3、业务之外的虚拟授权
4、and so on...

Java  Spring 
更新时间:2023-06-21 20:03:12

本文由 新逸Cary 创作,如果您觉得本文不错,请随意赞赏
采用 知识共享署名4.0 国际许可协议进行许可
本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名
原文链接:https://blog.xinac.cn/archives/spring-security-authentication.html
最后更新:2023-06-21 20:03:12

评论

Your browser is out of date!

Update your browser to view this website correctly. Update my browser now

×