文章目录
提示:以下是本篇文章正文内容,下面案例可供参考
一、认证流程图
一、认证流程源码分析
AbstractAuthenticationProcessingFilter
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest)req;
HttpServletResponse response = (HttpServletResponse)res;
// 判断是否是需要验证方法(是否是登陆的请求),不是的话直接放过
if (!this.requiresAuthentication(request, response)) {
chain.doFilter(request, response);
} else {
// 登陆的请求开始进行验证
Authentication authResult;
try {
//开始认证
authResult = this.attemptAuthentication(request, response);
//认证失败处理
if (authResult == null) {
return;
}
}
this.successfulAuthentication(request, response, chain, authResult);
}
}
UsernamePasswordAuthenticationFilter.attemptAuthentication
public Authentication attemptAuthentication(HttpServletRequest request,
HttpServletResponse response) throws AuthenticationException {
//请求方式不是post就抛出异常
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);
}
}
this.getAuthenticationManager().authenticate 就是 ProviderManager.authenticate
result = provider.authenticate(authentication);
if (result != null) {
this.copyDetails(authentication, result);
break;
}
provider.authenticate 就是 AbstractUserDetailsAuthenticationProvider.authenticate
//从数据库获取user
user = this.retrieveUser(username, (UsernamePasswordAuthenticationToken)authentication);
//校验密码
this.additionalAuthenticationChecks(user, (UsernamePasswordAuthenticationToken)authentication);
this.retrieveUser 就是 DaoAuthenticationProvider.retrieveUser
UserDetails loadedUser = this.getUserDetailsService().loadUserByUsername(username);