SpringSecurity-4-认证流程源码解析

本文涉及的产品
云解析 DNS,旗舰版 1个月
全局流量管理 GTM,标准版 1个月
公共DNS(含HTTPDNS解析),每月1000万次HTTP解析
简介: SpringSecurity-4-认证流程源码解析

SpringSecurity-4-认证流程源码解析

登录认证基本原理

Spring Security的登录验证核心过滤链如图所示



2bd44198206e87087fcde2a28402bcd7.png

请求阶段


SpringSecurity过滤器链始终贯穿一个上下文SecurityContext和一个Authentication对象(登录认证主体)。


只有请求主体通过某一个过滤器认证,Authentication对象就会被填充,如果验证通过isAuthenticated=true


如果请求通过了所有的过滤器,但是没有被认证,那么在最后有一个FilterSecurityInterceptor过滤器(名字看起来是拦截器,实际上是一个过滤器),来判断Authentication的认证状态,如果isAuthenticated=false(认证失败),则抛出认证异常。


响应阶段


响应阶段,如果FilterSecurityInterceptor抛出异常,则会被ExceptionTranslationFilter进行相应的处理,例如:用户名密码登录异常,然后被重新跳转到登录页面。


如果登录成功,请求响应会在SecurityContextPersistenceFilter过滤器中将返回的authentication的信息,如果有就放入session中,在下次请求的时候,就会直接从SecurityContextPersistenceFilter过滤器的session中获取认证信息,避免重复多次认证。


SpringSecurity多种登录认证方式


SpringSecurity使用Filter实现了多种登录认证方式,如下:


BasicAuthenticationFilter认证HttpBasic登录认证模式


UsernamePasswordAuthenticationFilter实现用户名密码登录认证


RememberMeAuthenticationFilter实现记住我功能


SocialAuthenticationFilter实现第三方社交登录认证,如微信,微博


Oauth2AuthenticationProcessingFilter实现Oauth2的鉴权方式


认证流程源码分析

认证流程图



6aa5d002dc1ed72da107e1328a19eddc.png


如图所示,用户登录使用用户密码登录认证方式的(其他认证方式也可以)。UsernamePassword AuthenticationFilter会使用用户名和密码创建一个UsernamePasswordAuthenticationToken作为登录凭证,从而获取Authentication对象,Authentication代码身份验证主体,贯穿用户认证流程始终。


UsernamePasswordAuthenticationFilter

UsernamePasswordAuthenticationFilter过滤器中用于获取Authentication实体的方法是attemptAuthentication,其源码分析如下:

22dfff87d8fe4012930d328567c057e3.png

 @Override
    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());
        }
        //从 request 中获取用户名、密码
        String username = obtainUsername(request);
        username = (username != null) ? username : "";
        username = username.trim();
        String password = obtainPassword(request);
        password = (password != null) ? password : "";
        // 将username和 password 构造成一个 UsernamePasswordAuthenticationToken 实例,
        // 其中构建器中会是否认证设置为 authenticated=false
        UsernamePasswordAuthenticationToken authRequest = new
                UsernamePasswordAuthenticationToken(username, password);
        //向 authRequest 对象中设置详细属性值。如添加了 remoteAddress、sessionId 值
        setDetails(request, authRequest);
        //调用 AuthenticationManager 的实现类 ProviderManager 进行验证
        return this.getAuthenticationManager().authenticate(authRequest);
    }

多种认证方式的ProviderManager

AuthenticationManager接口是对登录认证主体进行authenticate认证的,源码如下

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


ProviderManager实现了AuthenticationManager的登录验证核心类,主要代码如下

public class ProviderManager implements AuthenticationManager, MessageSourceAware, InitializingBean {
 private static final Log logger = LogFactory.getLog(ProviderManager.class);
 private List<AuthenticationProvider> providers = Collections.emptyList();
 @Override
 public Authentication authenticate(Authentication authentication) throws AuthenticationException {
  //获取当前的Authentication的认证类型
        Class<? extends Authentication> toTest = authentication.getClass();
  AuthenticationException lastException = null;
  AuthenticationException parentException = null;
  Authentication result = null;
  Authentication parentResult = null;
  int currentPosition = 0;
  int size = this.providers.size();
        // 迭代认证提供者,不同认证方式有不同提供者,如:用户名密码认证提供者,手机短信认证提供者
  for (AuthenticationProvider provider : getProviders()) {
            // 选取当前认证方式对应的提供者
   if (!provider.supports(toTest)) {
    continue;
   }
   if (logger.isTraceEnabled()) {
    logger.trace(LogMessage.format("Authenticating request with %s (%d/%d)",
      provider.getClass().getSimpleName(), ++currentPosition, size));
   }
   try {
                // 进行认证操作
                // AbstractUserDetailsAuthenticationProvider》DaoAuthenticationProvider
    result = provider.authenticate(authentication);
    if (result != null) {
                    //认证通过的话,将认证结果的details赋值到当前认证对象authentication。然后跳出循环
     copyDetails(authentication, result);
     break;
    }
   }
   catch (AccountStatusException | InternalAuthenticationServiceException ex) {
    prepareException(ex, authentication);
    // SEC-546: Avoid polling additional providers if auth failure is due to
    // invalid account status
    throw ex;
   }
   catch (AuthenticationException ex) {
    lastException = ex;
   }
  }
  if (result == null && this.parent != null) {
   // Allow the parent to try.
   try {
    parentResult = this.parent.authenticate(authentication);
    result = parentResult;
   }
   catch (ProviderNotFoundException ex) {
    // ignore as we will throw below if no other exception occurred prior to
    // calling parent and the parent
    // may throw ProviderNotFound even though a provider in the child already
    // handled the request
   }
   catch (AuthenticationException ex) {
    parentException = ex;
    lastException = ex;
   }
  }
  if (result != null) {
   if (this.eraseCredentialsAfterAuthentication && (result instanceof CredentialsContainer)) {
    // Authentication is complete. Remove credentials and other secret data
    // from authentication
    ((CredentialsContainer) result).eraseCredentials();
   }
   // If the parent AuthenticationManager was attempted and successful then it
   // will publish an AuthenticationSuccessEvent
   // This check prevents a duplicate AuthenticationSuccessEvent if the parent
   // AuthenticationManager already published it
   if (parentResult == null) {
    this.eventPublisher.publishAuthenticationSuccess(result);
   }
   return result;
  }
  // Parent was null, or didn't authenticate (or throw an exception).
  if (lastException == null) {
   lastException = new ProviderNotFoundException(this.messages.getMessage("ProviderManager.providerNotFound",
     new Object[] { toTest.getName() }, "No AuthenticationProvider found for {0}"));
  }
  // If the parent AuthenticationManager was attempted and failed then it will
  // publish an AbstractAuthenticationFailureEvent
  // This check prevents a duplicate AbstractAuthenticationFailureEvent if the
  // parent AuthenticationManager already published it
  if (parentException == null) {
   prepareException(lastException, authentication);
  }
  throw lastException;
 }
 @SuppressWarnings("deprecation")
 private void prepareException(AuthenticationException ex, Authentication auth) {
  this.eventPublisher.publishAuthenticationFailure(ex, auth);
 }
 public List<AuthenticationProvider> getProviders() {
  return this.providers;
 }
}

请注意查看我的中文注释

AuthenticationProvider



认证是由 AuthenticationManager 来管理的,真正进行认证的是 AuthenticationManager 中定义的 AuthenticationProvider,每一种登录认证方式都可以尝试对登录认证主体进行认证。只要有一种方式被认证成功,Authentication对象就成为被认可的主体,Spring Security 默认会使用 DaoAuthenticationProvider

public interface AuthenticationProvider {
 Authentication authenticate(Authentication authentication) throws AuthenticationException;
 boolean supports(Class<?> authentication);
}

AuthenticationProvider的接口实现有多种,如图所示

  • RememberMeAuthenticationProvider定义了“记住我”功能的登录验证逻辑
  • DaoAuthenticationProvider加载数据库用户信息,进行用户密码的登录验证


DaoAuthenticationProvider


DaoAuthenticationProvider使用数据库加载用户信息 ,源码如下图

6dbca2248e84388f0b5ed25fd7ab214e.png



我们发现DaoAuthenticationProvider继承了AbstractUserDetailsAuthenticationProvider;AbstractUserDetailsAuthenticationProvider是一个抽象类,是 AuthenticationProvider 的核心实现类,实现了DaoAuthenticationProvider类中的authenticate方法,代码如下

AbstractUserDetailsAuthenticationProvider

AbstractUserDetailsAuthenticationProvide的Authentication方法源码

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
   //如果authentication不是UsernamePasswordAuthenticationToken类型,则抛出异常
   Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication,
         () -> this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.onlySupports",
               "Only UsernamePasswordAuthenticationToken is supported"));\
   // 获取用户名
   String username = determineUsername(authentication);
   boolean cacheWasUsed = true;
   //从缓存中获取UserDetails
   UserDetails user = this.userCache.getUserFromCache(username);
   //当缓存中没有UserDetails,则从子类DaoAuthenticationProvider中获取
   if (user == null) {
      cacheWasUsed = false;
      try {
         //子类DaoAuthenticationProvider中实现获取用户信息, 
         // 就是调用对应UserDetailsService#loadUserByUsername
         user = retrieveUser(username, (UsernamePasswordAuthenticationToken) authentication);
      }
      catch (UsernameNotFoundException ex) {
        ...
      }
      ...
   }
   try {
       //前置检查。DefaultPreAuthenticationChecks 检测帐户是否锁定,是否可用,是否过期
      this.preAuthenticationChecks.check(user);
      // 检查密码是否正确
      additionalAuthenticationChecks(user, (UsernamePasswordAuthenticationToken) authentication);
   }
   catch (AuthenticationException ex) {
       // 异常则是重新认证
      if (!cacheWasUsed) {
         throw ex;
      }
      cacheWasUsed = false;
       // 调用 loadUserByUsername 查询登录用户信息
      user = retrieveUser(username, (UsernamePasswordAuthenticationToken) authentication);
      this.preAuthenticationChecks.check(user);
      additionalAuthenticationChecks(user, (UsernamePasswordAuthenticationToken) authentication);
   }
    //后检查。由DefaultPostAuthenticationChecks实现(检测密码是否过期)
   this.postAuthenticationChecks.check(user);
   if (!cacheWasUsed) {//是否放到缓存中
      this.userCache.putUserInCache(user);
   }
   Object principalToReturn = user;
   if (this.forcePrincipalAsString) {
      principalToReturn = user.getUsername();
   }
    //将认证成功用户信息封装成 UsernamePasswordAuthenticationToken 对象并返回
   return createSuccessAuthentication(principalToReturn, authentication, user);
}



DaoAuthenticationProvider从数据库获取用户信息

DaoAuthenticationProvider类中的retrieveUser方法

当我们需要使用数据库方式加载用户信息的时候,我么就需要实现UserDetailsService接口,重写loadUserByUsername方法


SecurityContext


登录认证完成以后,就需要Authtication信息,放入到SecurityContext中,后续就直接从SecurityContextFilter获取认证,避免重复多次认证。


注:注意查看我代码中的中文注释


如果您觉得本文不错,欢迎关注,点赞,收藏支持,您的关注是我坚持的动力!

目录
相关文章
|
13天前
|
存储 缓存 Java
什么是线程池?从底层源码入手,深度解析线程池的工作原理
本文从底层源码入手,深度解析ThreadPoolExecutor底层源码,包括其核心字段、内部类和重要方法,另外对Executors工具类下的四种自带线程池源码进行解释。 阅读本文后,可以对线程池的工作原理、七大参数、生命周期、拒绝策略等内容拥有更深入的认识。
什么是线程池?从底层源码入手,深度解析线程池的工作原理
|
17天前
|
开发工具
Flutter-AnimatedWidget组件源码解析
Flutter-AnimatedWidget组件源码解析
|
13天前
|
设计模式 Java 关系型数据库
【Java笔记+踩坑汇总】Java基础+JavaWeb+SSM+SpringBoot+SpringCloud+瑞吉外卖/谷粒商城/学成在线+设计模式+面试题汇总+性能调优/架构设计+源码解析
本文是“Java学习路线”专栏的导航文章,目标是为Java初学者和初中高级工程师提供一套完整的Java学习路线。
156 37
|
5天前
|
编解码 开发工具 UED
QT Widgets模块源码解析与实践
【9月更文挑战第20天】Qt Widgets 模块是 Qt 开发中至关重要的部分,提供了丰富的 GUI 组件,如按钮、文本框等,并支持布局管理、事件处理和窗口管理。这些组件基于信号与槽机制,实现灵活交互。通过对源码的解析及实践应用,可深入了解其类结构、布局管理和事件处理机制,掌握创建复杂 UI 界面的方法,提升开发效率和用户体验。
45 12
|
1天前
|
监控 数据挖掘 BI
项目管理流程全解析及关键步骤介绍
项目管理流程是项目成功的基石,涵盖启动、规划、执行、监控和收尾等阶段。Zoho Projects 等软件可提高效率,支持结构化启动与规划、高效执行与协作及实时监控。这些流程和工具对项目的全局视角、团队协作和风险控制至关重要。项目管理软件适用于不同规模企业,实施时间因软件复杂度和企业准备而异。
11 2
手机上网流程解析
【9月更文挑战第5天】
|
27天前
|
持续交付 jenkins Devops
WPF与DevOps的完美邂逅:从Jenkins配置到自动化部署,全流程解析持续集成与持续交付的最佳实践
【8月更文挑战第31天】WPF与DevOps的结合开启了软件生命周期管理的新篇章。通过Jenkins等CI/CD工具,实现从代码提交到自动构建、测试及部署的全流程自动化。本文详细介绍了如何配置Jenkins来管理WPF项目的构建任务,确保每次代码提交都能触发自动化流程,提升开发效率和代码质量。这一方法不仅简化了开发流程,还加强了团队协作,是WPF开发者拥抱DevOps文化的理想指南。
47 1
|
18天前
|
缓存 网络协议 Linux
DNS的执行流程是什么?
DNS的执行流程是什么?
28 0
|
28天前
|
监控 网络协议 Java
Tomcat源码解析】整体架构组成及核心组件
Tomcat,原名Catalina,是一款优雅轻盈的Web服务器,自4.x版本起扩展了JSP、EL等功能,超越了单纯的Servlet容器范畴。Servlet是Sun公司为Java编程Web应用制定的规范,Tomcat作为Servlet容器,负责构建Request与Response对象,并执行业务逻辑。
Tomcat源码解析】整体架构组成及核心组件
|
1月前
|
存储 NoSQL Redis
redis 6源码解析之 object
redis 6源码解析之 object
55 6

热门文章

最新文章

推荐镜像

更多