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

简介: 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获取认证,避免重复多次认证。


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


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

目录
相关文章
|
9月前
|
存储 域名解析 弹性计算
阿里云上云流程参考:云服务器+域名+备案+域名解析绑定,全流程图文详解
对于初次通过阿里云完成上云的企业和个人用户来说,很多用户不仅是需要选购云服务器,同时还需要注册域名以及完成备案和域名的解析相关流程,从而实现网站的上线。本文将以上云操作流程为核心,结合阿里云的活动政策与用户系统梳理云服务器选购、域名注册、备案申请及域名绑定四大关键环节,以供用户完成线上业务部署做出参考。
|
算法 测试技术 C语言
深入理解HTTP/2:nghttp2库源码解析及客户端实现示例
通过解析nghttp2库的源码和实现一个简单的HTTP/2客户端示例,本文详细介绍了HTTP/2的关键特性和nghttp2的核心实现。了解这些内容可以帮助开发者更好地理解HTTP/2协议,提高Web应用的性能和用户体验。对于实际开发中的应用,可以根据需要进一步优化和扩展代码,以满足具体需求。
1445 29
|
监控 Shell Linux
Android调试终极指南:ADB安装+多设备连接+ANR日志抓取全流程解析,覆盖环境变量配置/多设备调试/ANR日志分析全流程,附Win/Mac/Linux三平台解决方案
ADB(Android Debug Bridge)是安卓开发中的重要工具,用于连接电脑与安卓设备,实现文件传输、应用管理、日志抓取等功能。本文介绍了 ADB 的基本概念、安装配置及常用命令。包括:1) 基本命令如 `adb version` 和 `adb devices`;2) 权限操作如 `adb root` 和 `adb shell`;3) APK 操作如安装、卸载应用;4) 文件传输如 `adb push` 和 `adb pull`;5) 日志记录如 `adb logcat`;6) 系统信息获取如屏幕截图和录屏。通过这些功能,用户可高效调试和管理安卓设备。
10349 2
|
前端开发 数据安全/隐私保护 CDN
二次元聚合短视频解析去水印系统源码
二次元聚合短视频解析去水印系统源码
565 4
|
JavaScript 算法 前端开发
JS数组操作方法全景图,全网最全构建完整知识网络!js数组操作方法全集(实现筛选转换、随机排序洗牌算法、复杂数据处理统计等情景详解,附大量源码和易错点解析)
这些方法提供了对数组的全面操作,包括搜索、遍历、转换和聚合等。通过分为原地操作方法、非原地操作方法和其他方法便于您理解和记忆,并熟悉他们各自的使用方法与使用范围。详细的案例与进阶使用,方便您理解数组操作的底层原理。链式调用的几个案例,让您玩转数组操作。 只有锻炼思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~
|
移动开发 前端开发 JavaScript
从入门到精通:H5游戏源码开发技术全解析与未来趋势洞察
H5游戏凭借其跨平台、易传播和开发成本低的优势,近年来发展迅猛。接下来,让我们深入了解 H5 游戏源码开发的技术教程以及未来的发展趋势。
|
存储 前端开发 JavaScript
在线教育网课系统源码开发指南:功能设计与技术实现深度解析
在线教育网课系统是近年来发展迅猛的教育形式的核心载体,具备用户管理、课程管理、教学互动、学习评估等功能。本文从功能和技术两方面解析其源码开发,涵盖前端(HTML5、CSS3、JavaScript等)、后端(Java、Python等)、流媒体及云计算技术,并强调安全性、稳定性和用户体验的重要性。
|
负载均衡 JavaScript 前端开发
分片上传技术全解析:原理、优势与应用(含简单实现源码)
分片上传通过将大文件分割成多个小的片段或块,然后并行或顺序地上传这些片段,从而提高上传效率和可靠性,特别适用于大文件的上传场景,尤其是在网络环境不佳时,分片上传能有效提高上传体验。 博客不应该只有代码和解决方案,重点应该在于给出解决方案的同时分享思维模式,只有思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~
|
设计模式 存储 安全
【23种设计模式·全精解析 | 创建型模式篇】5种创建型模式的结构概述、实现、优缺点、扩展、使用场景、源码解析
结构型模式描述如何将类或对象按某种布局组成更大的结构。它分为类结构型模式和对象结构型模式,前者采用继承机制来组织接口和类,后者釆用组合或聚合来组合对象。由于组合关系或聚合关系比继承关系耦合度低,满足“合成复用原则”,所以对象结构型模式比类结构型模式具有更大的灵活性。 结构型模式分为以下 7 种: • 代理模式 • 适配器模式 • 装饰者模式 • 桥接模式 • 外观模式 • 组合模式 • 享元模式
909 140
【23种设计模式·全精解析 | 创建型模式篇】5种创建型模式的结构概述、实现、优缺点、扩展、使用场景、源码解析

推荐镜像

更多
  • DNS