本文共 2142 字,大约阅读时间需要 7 分钟。
UsernamePasswordAuthenticationFilter
是 AbstractAuthenticationProcessingFilter
的子类,主要作用是对用户身份信息的验证。
AbstractAuthenticationProcessingFilter
的分析见此: 。 UsernamePasswordAuthenticationFilter
继承自AbstractAuthenticationProcessingFilter
。
public class UsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
AbstractAuthenticationProcessingFilter
是处理 form 登陆的过滤器,与 form 登陆有关的所有操作都是在该类中及其子类中进行的。
关于 UsernamePasswordAuthenticationFilter
处理请求的大体流程和其父类一致,见此: 。该处主要分析UsernamePasswordAuthenticationFilter
实现的父类方法 attemptAuthentication()
中的用户身份验证逻辑。
attemptAuthentication()
方法代码如下所示: public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { if (postOnly && !request.getMethod().equals("POST")) { throw new AuthenticationServiceException( "Authentication method not supported: " + request.getMethod()); }-->1 String username = obtainUsername(request);-->2 String password = obtainPassword(request); if (username == null) { username = ""; } if (password == null) { password = ""; } username = username.trim();-->3 UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken( username, password); // Allow subclasses to set the "details" property setDetails(request, authRequest);-->4 return this.getAuthenticationManager().authenticate(authRequest); }
-->1
和 -->2
处的代码从 request
中提取用户名和密码。-->3
处代码为构建类UsernamePasswordAuthenticationToken
成员变量,UsernamePasswordAuthenticationToken
是一个用户信息的载体类,用来存储及传递用户名和用户密码。-->4
处代码调用getAuthenticationManager()
方法获取AuthenticationManager
实例,getAuthenticationManager()
方法定义如下:protected AuthenticationManager getAuthenticationManager() { return authenticationManager; }
然后调用获取到的AuthenticationManager
实例的authenticate()
方法对封装在authRequest [UsernamePasswordAuthenticationToken]
中的用户名及密码进行验证。
注意:
AuthenticationManager
这里可以理解为 spring security 配置文件中<authentication-manager/>
的实现类。
attemptAuthentication 验证函数流程图.png
转载地址:http://nhwci.baihongyu.com/