认证流程源码杂记

认证流程源码

认证处理流程说明
认证结果如何在多个请求之间共享
获取认证用户信息
认证流程源码杂记

首选是UsernamePasswordAuthenticationFilter 
获取到请求中携带的用户名和密码,然后构建一个UsernamePasswordAuthenticationToken 对象
public class UsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
    if (this.postOnly && !request.getMethod().equals("POST")) {
        throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
    } else {
        String username = this.obtainUsername(request);
        String password = this.obtainPassword(request);
        if (username == null) {
            username = "";
        }

        if (password == null) {
            password = "";
        }

        username = username.trim();
        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
        this.setDetails(request, authRequest);
        return this.getAuthenticationManager().authenticate(authRequest);
    }
}
}




public class UsernamePasswordAuthenticationToken extends AbstractAuthenticationToken


public interface AuthenticationManager {
    Authentication authenticate(Authentication var1) throws AuthenticationException;
}


public class ProviderManager implements AuthenticationManager, MessageSourceAware, InitializingBean

认证流程源码杂记

DaoAuthenticationProvider

认证流程源码杂记
认证流程源码杂记

认证流程源码杂记

AbstractAuthenticationProcessingFilter
认证流程源码杂记

SecurityContextImpl

认证流程源码杂记

认证流程源码杂记

拿到用户登录信息

@RequestMapping("user")
//每个方法的路径前面都有一个user 可以抽取出来放到类上 ,spring 会将类上的路径+方法上的路径 作为访问路径
@RestController
public class UserController implements Serializable {


    @GetMapping("/me")
    public Object getCurrentUser(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return  authentication;
    }

    @GetMapping("/me1")
    public Object getCurrentUser1(Authentication authentication ){
        //spring 会自动找到Authentication类型的数据注入
        return  authentication;
    }

    @GetMapping("/me2")
    public Object getCurrentUser2(@AuthenticationPrincipal UserDetails user){
        return user;
    }

认证流程源码杂记