认证流程

(六)Spring Security 认证流程 - 图1
图片来自于:黑马程序员 SpringSecurity 认证课程

认证过程:

  1. 用户提交用户名、密码被 SecurityFilterChain 中的 UsernamePasswordAuthenticationFilter 过滤器获取到,封装为请求 Authentication,通常情况下是 UsernamePasswordAuthenticationToken 这个实现类。
  2. 然后过滤器将 Authentication 提交至认证管理器(AuthenticationManager)进行认证
  3. 认证成功后, AuthenticationManager 身份管理器返回一个被填充满了信息的(包括上面提到的权限信息,身份信息,细节信息,但密码通常会被移除) Authentication 实例。
  4. SecurityContextHolder 安全上下文容器将第 3 步填充了信息的 Authentication ,通过 SecurityContextHolder.getContext().setAuthentication(…) 方法,设置到其中。可以看出 AuthenticationManager 接口(认证管理器)是认证相关的核心接口,也是发起认证的出发点,它
    的实现类为 ProviderManager。而 Spring Security 支持多种认证方式,因此 ProviderManager 维护着一个
    List 列表,存放多种认证方式,最终实际的认证工作是由
    AuthenticationProvider 完成的。咱们知道 web 表单的对应的 AuthenticationProvider 实现类为
    DaoAuthenticationProvider,它的内部又维护着一个 UserDetailsService 负责 UserDetails 的获取。最终
    AuthenticationProvider 将 UserDetails 填充至 Authentication。
    认证核心组件的大体关系如下:
    (六)Spring Security 认证流程 - 图2
    图片来自于:黑马程序员 SpringSecurity 认证课程

知识点认识

Authentication

我们所面对的系统中的用户,在 Spring Security 中被称为主体(principal)。主体包含了所有能够经过验证而获得系统访问权限的用户、设备或其他系统。主体的概念实际上来自 Java Security,Spring Security 通过一层包装将其定义为一个 Authentication。

  1. public interface Authentication extends Principal, Serializable {
  2. // 获取主体授权列表
  3. Collection<? extends GrantedAuthority> getAuthorities();
  4. // 获取主体凭证,一般为密码
  5. Object getCredentials();
  6. // 获取主体携带的详细信息
  7. Object getDetails();
  8. // 获取主体,通常为username
  9. Object getPrincipal();
  10. // 获取当前主体是否认证成功
  11. boolean isAuthenticated();
  12. // 设置当前主体是否认证成功状态
  13. void setAuthenticated(boolean var1) throws IllegalArgumentException;
  14. }

AuthenticateProvider

Spring Security 认证的过程其实就是一个构建 Authentication 的过程。Authentication 在 Spring Security 的各个 AuthenticationProvider 中流动,AuthenticationProvider 被 Spring Security 定义为一个验证过程:

  1. public interface AuthenticationProvider {
  2. // 验证完成,成功,返回一个验证完成的Authentication
  3. Authentication authenticate(Authentication var1) throws AuthenticationException;
  4. // 是否支持验证当前的Authentication类型
  5. boolean supports(Class<?> var1);
  6. }

大部分场景下身份验证都是基于用户名和密码进行的,所以 Spring Security 提供了一个 UsernamePasswordAuthenticationToken 用于代指这一类证。,每一个登录用户即主体都被包装为一个 UsernamePasswordAuthenticationToken,从而在 Spring Security 的各个 AuthenticationProvider 中流动。

ProviderManager

一次完整的认证可以包含多个 AuthenticationProvider,一般由 ProviderManager 管理。

  1. public class ProviderManager implements AuthenticationManager, MessageSourceAware, InitializingBean {
  2. private static final Log logger = LogFactory.getLog(ProviderManager.class);
  3. private AuthenticationEventPublisher eventPublisher;
  4. // AuthenticationProvider 列表
  5. private List<AuthenticationProvider> providers;
  6. protected MessageSourceAccessor messages;
  7. private AuthenticationManager parent;
  8. private boolean eraseCredentialsAfterAuthentication;
  9. public ProviderManager(List<AuthenticationProvider> providers) {
  10. this(providers, (AuthenticationManager)null);
  11. }
  12. public ProviderManager(List<AuthenticationProvider> providers, AuthenticationManager parent) {
  13. this.eventPublisher = new ProviderManager.NullEventPublisher();
  14. this.providers = Collections.emptyList();
  15. this.messages = SpringSecurityMessageSource.getAccessor();
  16. this.eraseCredentialsAfterAuthentication = true;
  17. Assert.notNull(providers, "providers list cannot be null");
  18. this.providers = providers;
  19. this.parent = parent;
  20. this.checkState();
  21. }
  22. public void afterPropertiesSet() {
  23. this.checkState();
  24. }
  25. private void checkState() {
  26. if (this.parent == null && this.providers.isEmpty()) {
  27. throw new IllegalArgumentException("A parent AuthenticationManager or a list of AuthenticationProviders is required");
  28. }
  29. }
  30. // 迭代AuthenticationProvider 列表,进行认证,返回最终结果
  31. public Authentication authenticate(Authentication authentication) throws AuthenticationException {
  32. Class<? extends Authentication> toTest = authentication.getClass();
  33. AuthenticationException lastException = null;
  34. AuthenticationException parentException = null;
  35. Authentication result = null;
  36. Authentication parentResult = null;
  37. boolean debug = logger.isDebugEnabled();
  38. Iterator var8 = this.getProviders().iterator();
  39. // 迭代
  40. while(var8.hasNext()) {
  41. AuthenticationProvider provider = (AuthenticationProvider)var8.next();
  42. // 判断AuthenticationProvider 是否支持当前验证
  43. if (provider.supports(toTest)) {
  44. if (debug) {
  45. logger.debug("Authentication attempt using " + provider.getClass().getName());
  46. }
  47. try {
  48. // 执行AuthenticationProvider的认证。
  49. result = provider.authenticate(authentication);
  50. if (result != null) {
  51. this.copyDetails(authentication, result);
  52. // 有一个验证通过,就返回
  53. break;
  54. }
  55. } catch (InternalAuthenticationServiceException | AccountStatusException var13) {
  56. this.prepareException(var13, authentication);
  57. throw var13;
  58. } catch (AuthenticationException var14) {
  59. lastException = var14;
  60. }
  61. }
  62. }
  63. if (result == null && this.parent != null) {
  64. try {
  65. result = parentResult = this.parent.authenticate(authentication);
  66. } catch (ProviderNotFoundException var11) {
  67. } catch (AuthenticationException var12) {
  68. parentException = var12;
  69. lastException = var12;
  70. }
  71. }
  72. if (result != null) {
  73. if (this.eraseCredentialsAfterAuthentication && result instanceof CredentialsContainer) {
  74. ((CredentialsContainer)result).eraseCredentials();
  75. }
  76. if (parentResult == null) {
  77. this.eventPublisher.publishAuthenticationSuccess(result);
  78. }
  79. return result;
  80. } else {
  81. if (lastException == null) {
  82. lastException = new ProviderNotFoundException(this.messages.getMessage("ProviderManager.providerNotFound", new Object[]{toTest.getName()}, "No AuthenticationProvider found for {0}"));
  83. }
  84. if (parentException == null) {
  85. this.prepareException((AuthenticationException)lastException, authentication);
  86. }
  87. throw lastException;
  88. }
  89. }
  90. private void prepareException(AuthenticationException ex, Authentication auth) {
  91. this.eventPublisher.publishAuthenticationFailure(ex, auth);
  92. }
  93. private void copyDetails(Authentication source, Authentication dest) {
  94. if (dest instanceof AbstractAuthenticationToken && dest.getDetails() == null) {
  95. AbstractAuthenticationToken token = (AbstractAuthenticationToken)dest;
  96. token.setDetails(source.getDetails());
  97. }
  98. }
  99. public List<AuthenticationProvider> getProviders() {
  100. return this.providers;
  101. }
  102. public void setMessageSource(MessageSource messageSource) {
  103. this.messages = new MessageSourceAccessor(messageSource);
  104. }
  105. public void setAuthenticationEventPublisher(AuthenticationEventPublisher eventPublisher) {
  106. Assert.notNull(eventPublisher, "AuthenticationEventPublisher cannot be null");
  107. this.eventPublisher = eventPublisher;
  108. }
  109. public void setEraseCredentialsAfterAuthentication(boolean eraseSecretData) {
  110. this.eraseCredentialsAfterAuthentication = eraseSecretData;
  111. }
  112. public boolean isEraseCredentialsAfterAuthentication() {
  113. return this.eraseCredentialsAfterAuthentication;
  114. }
  115. private static final class NullEventPublisher implements AuthenticationEventPublisher {
  116. private NullEventPublisher() {
  117. }
  118. public void publishAuthenticationFailure(AuthenticationException exception, Authentication authentication) {
  119. }
  120. public void publishAuthenticationSuccess(Authentication authentication) {
  121. }
  122. }
  123. }

自定义 AuthenticationProvider

Spring Security 提供了多种常见的认证技术,包括但不限于以下几种:

  • HTTP 层面的认证技术,包括 HTTP 基本认证和 HTTP 摘要认证两种。
  • 基于 LDAP 的认证技术(Lightweight Directory Access Protocol,轻量目录访问协议)。
  • 聚焦于证明用户身份的 OpenID 认证技术。
  • 聚焦于授权的 OAuth 认证技术。
  • 系统内维护的用户名和密码认证技术。
    其中,使用最为广泛的是由系统维护的用户名和密码认证技术,通常会涉及数据库访问。为了更好地按需定制,Spring Security 并没有直接糅合整个认证过程,而是提供了一个抽象的 AuthenticationProvider,AbstractUserDetailsAuthenticationProvider:
  1. public abstract class AbstractUserDetailsAuthenticationProvider implements AuthenticationProvider, InitializingBean, MessageSourceAware {
  2. protected final Log logger = LogFactory.getLog(this.getClass());
  3. protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
  4. private UserCache userCache = new NullUserCache();
  5. private boolean forcePrincipalAsString = false;
  6. protected boolean hideUserNotFoundExceptions = true;
  7. private UserDetailsChecker preAuthenticationChecks = new AbstractUserDetailsAuthenticationProvider.DefaultPreAuthenticationChecks();
  8. private UserDetailsChecker postAuthenticationChecks = new AbstractUserDetailsAuthenticationProvider.DefaultPostAuthenticationChecks();
  9. private GrantedAuthoritiesMapper authoritiesMapper = new NullAuthoritiesMapper();
  10. public AbstractUserDetailsAuthenticationProvider() {
  11. }
  12. // 附件认证过程
  13. protected abstract void additionalAuthenticationChecks(UserDetails var1, UsernamePasswordAuthenticationToken var2) throws AuthenticationException;
  14. public final void afterPropertiesSet() throws Exception {
  15. Assert.notNull(this.userCache, "A user cache must be set");
  16. Assert.notNull(this.messages, "A message source must be set");
  17. this.doAfterPropertiesSet();
  18. }
  19. // 主体认证过程
  20. public Authentication authenticate(Authentication authentication) throws AuthenticationException {
  21. Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication, () -> {
  22. return this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.onlySupports", "Only UsernamePasswordAuthenticationToken is supported");
  23. });
  24. String username = authentication.getPrincipal() == null ? "NONE_PROVIDED" : authentication.getName();
  25. boolean cacheWasUsed = true;
  26. UserDetails user = this.userCache.getUserFromCache(username);
  27. if (user == null) {
  28. cacheWasUsed = false;
  29. try {
  30. // 先检索用户
  31. user = this.retrieveUser(username, (UsernamePasswordAuthenticationToken)authentication);
  32. } catch (UsernameNotFoundException var6) {
  33. this.logger.debug("User '" + username + "' not found");
  34. if (this.hideUserNotFoundExceptions) {
  35. throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
  36. }
  37. throw var6;
  38. }
  39. Assert.notNull(user, "retrieveUser returned null - a violation of the interface contract");
  40. }
  41. try {
  42. // 认证前检查,检查账号是否可用
  43. this.preAuthenticationChecks.check(user);
  44. // 执行附加认证
  45. this.additionalAuthenticationChecks(user, (UsernamePasswordAuthenticationToken)authentication);
  46. } catch (AuthenticationException var7) {
  47. if (!cacheWasUsed) {
  48. throw var7;
  49. }
  50. cacheWasUsed = false;
  51. user = this.retrieveUser(username, (UsernamePasswordAuthenticationToken)authentication);
  52. this.preAuthenticationChecks.check(user);
  53. this.additionalAuthenticationChecks(user, (UsernamePasswordAuthenticationToken)authentication);
  54. }
  55. // 认证后检查,一般是检查账号密码是否过期
  56. this.postAuthenticationChecks.check(user);
  57. if (!cacheWasUsed) {
  58. this.userCache.putUserInCache(user);
  59. }
  60. Object principalToReturn = user;
  61. if (this.forcePrincipalAsString) {
  62. principalToReturn = user.getUsername();
  63. }
  64. // 返回一个认证通过的Authentication
  65. return this.createSuccessAuthentication(principalToReturn, authentication, user);
  66. }
  67. protected Authentication createSuccessAuthentication(Object principal, Authentication authentication, UserDetails user) {
  68. UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(principal, authentication.getCredentials(), this.authoritiesMapper.mapAuthorities(user.getAuthorities()));
  69. result.setDetails(authentication.getDetails());
  70. return result;
  71. }
  72. protected void doAfterPropertiesSet() throws Exception {
  73. }
  74. public UserCache getUserCache() {
  75. return this.userCache;
  76. }
  77. public boolean isForcePrincipalAsString() {
  78. return this.forcePrincipalAsString;
  79. }
  80. public boolean isHideUserNotFoundExceptions() {
  81. return this.hideUserNotFoundExceptions;
  82. }
  83. // 检索用户
  84. protected abstract UserDetails retrieveUser(String var1, UsernamePasswordAuthenticationToken var2) throws AuthenticationException;
  85. public void setForcePrincipalAsString(boolean forcePrincipalAsString) {
  86. this.forcePrincipalAsString = forcePrincipalAsString;
  87. }
  88. public void setHideUserNotFoundExceptions(boolean hideUserNotFoundExceptions) {
  89. this.hideUserNotFoundExceptions = hideUserNotFoundExceptions;
  90. }
  91. public void setMessageSource(MessageSource messageSource) {
  92. this.messages = new MessageSourceAccessor(messageSource);
  93. }
  94. public void setUserCache(UserCache userCache) {
  95. this.userCache = userCache;
  96. }
  97. // 此认证支持UsernamePasswordAuthenticationToken及其衍生类认证
  98. public boolean supports(Class<?> authentication) {
  99. return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
  100. }
  101. protected UserDetailsChecker getPreAuthenticationChecks() {
  102. return this.preAuthenticationChecks;
  103. }
  104. public void setPreAuthenticationChecks(UserDetailsChecker preAuthenticationChecks) {
  105. this.preAuthenticationChecks = preAuthenticationChecks;
  106. }
  107. protected UserDetailsChecker getPostAuthenticationChecks() {
  108. return this.postAuthenticationChecks;
  109. }
  110. public void setPostAuthenticationChecks(UserDetailsChecker postAuthenticationChecks) {
  111. this.postAuthenticationChecks = postAuthenticationChecks;
  112. }
  113. public void setAuthoritiesMapper(GrantedAuthoritiesMapper authoritiesMapper) {
  114. this.authoritiesMapper = authoritiesMapper;
  115. }
  116. private class DefaultPostAuthenticationChecks implements UserDetailsChecker {
  117. private DefaultPostAuthenticationChecks() {
  118. }
  119. public void check(UserDetails user) {
  120. if (!user.isCredentialsNonExpired()) {
  121. AbstractUserDetailsAuthenticationProvider.this.logger.debug("User account credentials have expired");
  122. throw new CredentialsExpiredException(AbstractUserDetailsAuthenticationProvider.this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.credentialsExpired", "User credentials have expired"));
  123. }
  124. }
  125. }
  126. private class DefaultPreAuthenticationChecks implements UserDetailsChecker {
  127. private DefaultPreAuthenticationChecks() {
  128. }
  129. public void check(UserDetails user) {
  130. if (!user.isAccountNonLocked()) {
  131. AbstractUserDetailsAuthenticationProvider.this.logger.debug("User account is locked");
  132. throw new LockedException(AbstractUserDetailsAuthenticationProvider.this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.locked", "User account is locked"));
  133. } else if (!user.isEnabled()) {
  134. AbstractUserDetailsAuthenticationProvider.this.logger.debug("User account is disabled");
  135. throw new DisabledException(AbstractUserDetailsAuthenticationProvider.this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.disabled", "User is disabled"));
  136. } else if (!user.isAccountNonExpired()) {
  137. AbstractUserDetailsAuthenticationProvider.this.logger.debug("User account is expired");
  138. throw new AccountExpiredException(AbstractUserDetailsAuthenticationProvider.this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.expired", "User account has expired"));
  139. }
  140. }
  141. }
  142. }

在 AbstractUserDetailsAuthenticationProvider 中实现了基本的认证流程,通过继承 AbstractUserDetailsAuthenticationProvider,并实现 retrieveUser 和 additionalAuthenticationChecks 两个抽象方法即可自定义核心认证过程,灵活性非常高。示例,Spring Security 用于处理 UsernamePasswordAuthenticationToken 的 DaoAuthenticationProvider:

  1. public class DaoAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {
  2. private static final String USER_NOT_FOUND_PASSWORD = "userNotFoundPassword";
  3. // 密码加密
  4. private PasswordEncoder passwordEncoder;
  5. private volatile String userNotFoundEncodedPassword;
  6. // UserDetailsService 用来获取用户信息
  7. private UserDetailsService userDetailsService;
  8. private UserDetailsPasswordService userDetailsPasswordService;
  9. public DaoAuthenticationProvider() {
  10. this.setPasswordEncoder(PasswordEncoderFactories.createDelegatingPasswordEncoder());
  11. }
  12. // 添加附加认证
  13. @Override
  14. protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
  15. if (authentication.getCredentials() == null) {
  16. this.logger.debug("Authentication failed: no credentials provided");
  17. throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
  18. } else {
  19. String presentedPassword = authentication.getCredentials().toString();
  20. // 密码对比判断
  21. if (!this.passwordEncoder.matches(presentedPassword, userDetails.getPassword())) {
  22. this.logger.debug("Authentication failed: password does not match stored value");
  23. throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
  24. }
  25. }
  26. }
  27. protected void doAfterPropertiesSet() {
  28. Assert.notNull(this.userDetailsService, "A UserDetailsService must be set");
  29. }
  30. // 获取用户
  31. @Override
  32. protected final UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
  33. this.prepareTimingAttackProtection();
  34. try {
  35. UserDetails loadedUser = this.getUserDetailsService().loadUserByUsername(username);
  36. if (loadedUser == null) {
  37. throw new InternalAuthenticationServiceException("UserDetailsService returned null, which is an interface contract violation");
  38. } else {
  39. return loadedUser;
  40. }
  41. } catch (UsernameNotFoundException var4) {
  42. this.mitigateAgainstTimingAttack(authentication);
  43. throw var4;
  44. } catch (InternalAuthenticationServiceException var5) {
  45. throw var5;
  46. } catch (Exception var6) {
  47. throw new InternalAuthenticationServiceException(var6.getMessage(), var6);
  48. }
  49. }
  50. protected Authentication createSuccessAuthentication(Object principal, Authentication authentication, UserDetails user) {
  51. boolean upgradeEncoding = this.userDetailsPasswordService != null && this.passwordEncoder.upgradeEncoding(user.getPassword());
  52. if (upgradeEncoding) {
  53. String presentedPassword = authentication.getCredentials().toString();
  54. String newPassword = this.passwordEncoder.encode(presentedPassword);
  55. user = this.userDetailsPasswordService.updatePassword(user, newPassword);
  56. }
  57. return super.createSuccessAuthentication(principal, authentication, user);
  58. }
  59. private void prepareTimingAttackProtection() {
  60. if (this.userNotFoundEncodedPassword == null) {
  61. this.userNotFoundEncodedPassword = this.passwordEncoder.encode("userNotFoundPassword");
  62. }
  63. }
  64. private void mitigateAgainstTimingAttack(UsernamePasswordAuthenticationToken authentication) {
  65. if (authentication.getCredentials() != null) {
  66. String presentedPassword = authentication.getCredentials().toString();
  67. this.passwordEncoder.matches(presentedPassword, this.userNotFoundEncodedPassword);
  68. }
  69. }
  70. public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
  71. Assert.notNull(passwordEncoder, "passwordEncoder cannot be null");
  72. this.passwordEncoder = passwordEncoder;
  73. this.userNotFoundEncodedPassword = null;
  74. }
  75. protected PasswordEncoder getPasswordEncoder() {
  76. return this.passwordEncoder;
  77. }
  78. public void setUserDetailsService(UserDetailsService userDetailsService) {
  79. this.userDetailsService = userDetailsService;
  80. }
  81. protected UserDetailsService getUserDetailsService() {
  82. return this.userDetailsService;
  83. }
  84. public void setUserDetailsPasswordService(UserDetailsPasswordService userDetailsPasswordService) {
  85. this.userDetailsPasswordService = userDetailsPasswordService;
  86. }
  87. }

UserDetailsService

道 DaoAuthenticationProvider 处理了 web 表单的认证逻辑,认证成功后既得到一个 Authentication(UsernamePasswordAuthenticationToken 实现),里面包含了身份信息(Principal)。
这个身份信息就是一个 Object,大多数情况下它可以被强转为 UserDetails 对象。DaoAuthenticationProvider 中包含了一个 UserDetailsService 实例,它负责根据用户名提取用户信息 UserDetails(包含密码)。

而后 DaoAuthenticationProvider 会去对比 UserDetailsService 提取的用户密码与用户提交的密码是否匹配作为认证成功的关键依据。

因此可以通过将自定义的 UserDetailsService 公开为 spring bean 来定义自定义身份验证。

  1. public interface UserDetailsService {
  2. UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;
  3. }

PasswordEncoder

DaoAuthenticationProvider 认证处理器通过 UserDetailsService 获取到 UserDetails 后,它是如何与请求 Authentication 中的密码做对比呢?

在这里 Spring Security 为了适应多种多样的加密类型,又做了抽象,DaoAuthenticationProvider 通过 PasswordEncoder 接口的 matches 方法进行密码的对比,而具体的密码对比细节取决于实现:

  1. public interface PasswordEncoder {
  2. String encode(CharSequence var1);
  3. boolean matches(CharSequence var1, String var2);
  4. default boolean upgradeEncoding(String encodedPassword) {
  5. return false;
  6. }
  7. }

而 Spring Security 提供很多内置的 PasswordEncoder,能够开箱即用,使用某种 PasswordEncoder 只需要进行如下声明即可,如下:

  1. @Bean
  2. public PasswordEncoder passwordEncoder() {
  3. return NoOpPasswordEncoder.getInstance();
  4. }