UsernamePasswordAuthenticationFilter 源码分析

UsernamePasswordAuthenticationFilterAbstractAuthenticationProcessingFilter 的子类,主要作用是对用户身份信息的验证。
  关于 AbstractAuthenticationProcessingFilter 的分析见此: AbstractAuthenticationProcessingFilter 源码分析

继承关系

UsernamePasswordAuthenticationFilter 继承自AbstractAuthenticationProcessingFilter

public class UsernamePasswordAuthenticationFilter extends
        AbstractAuthenticationProcessingFilter {

AbstractAuthenticationProcessingFilter 是处理 form 登陆的过滤器,与 form 登陆有关的所有操作都是在该类中及其子类中进行的。

流程分析

关于 UsernamePasswordAuthenticationFilter 处理请求的大体流程和其父类一致,见此: AbstractAuthenticationProcessingFilter 源码分析。该处主要分析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

参考

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,293评论 19 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 47,014评论 6 342
  • 闪耀是自信吗 夺目是自信吗 争抢是自信吗 无礼是自信吗 哗众取宠是自信吗 毫不收敛是自信吗 伪装是自信吗 赤裸是自...
    天籁村阅读 890评论 0 0
  • 地址 传送门 说明 readline模块提供了一个接口,从readable流读取一行数据,比如process.st...
    一溪酒阅读 3,649评论 0 0
  • 好久不见,2016年第一篇,最近正在和团队的小伙伴一起处理一个复杂的表单设计,正好看到这篇文章,小有启发,就决定译...
    TerryFan阅读 5,966评论 2 7