浅析Spring Security认证过程

2024-09-09 18:18

本文主要是介绍浅析Spring Security认证过程,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

类图

为了方便理解Spring Security认证流程,特意画了如下的类图,包含相关的核心认证类

概述

核心验证器

AuthenticationManager

该对象提供了认证方法的入口,接收一个Authentiaton对象作为参数;

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

ProviderManager

它是 AuthenticationManager 的一个实现类,提供了基本的认证逻辑和方法;它包含了一个 List<AuthenticationProvider>对象,通过 AuthenticationProvider 接口来扩展出不同的认证提供者(当Spring Security默认提供的实现类不能满足需求的时候可以扩展AuthenticationProvider 覆盖supports(Class<?> authentication)方法);

验证逻辑

AuthenticationManager 接收 Authentication 对象作为参数,并通过 authenticate(Authentication) 方法对其进行验证;AuthenticationProvider实现类用来支撑对 Authentication 对象的验证动作;UsernamePasswordAuthenticationToken实现了 Authentication主要是将用户输入的用户名和密码进行封装,并供给 AuthenticationManager 进行验证;验证完成以后将返回一个认证成功的 Authentication 对象;

Authentication

Authentication对象中的主要方法

public interface Authentication extends Principal, Serializable {//#1.权限结合,可使用AuthorityUtils.commaSeparatedStringToAuthorityList("admin,ROLE_ADMIN")返回字符串权限集合Collection<? extends GrantedAuthority> getAuthorities();//#2.用户名密码认证时可以理解为密码Object getCredentials();//#3.认证时包含的一些信息。Object getDetails();//#4.用户名密码认证时可理解时用户名Object getPrincipal();#5.是否被认证,认证为true    boolean isAuthenticated();#6.设置是否能被认证void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException;

ProviderManager

ProviderManagerAuthenticationManager的实现类,提供了基本认证实现逻辑和流程;

public Authentication authenticate(Authentication authentication)throws AuthenticationException {//#1.获取当前的Authentication的认证类型Class<? extends Authentication> toTest = authentication.getClass();AuthenticationException lastException = null;Authentication result = null;boolean debug = logger.isDebugEnabled();//#2.遍历所有的providers使用supports方法判断该provider是否支持当前的认证类型,不支持的话继续遍历for (AuthenticationProvider provider : getProviders()) {if (!provider.supports(toTest)) {continue;}if (debug) {logger.debug("Authentication attempt using "+ provider.getClass().getName());}try {#3.支持的话调用provider的authenticat方法认证result = provider.authenticate(authentication);if (result != null) {#4.认证通过的话重新生成Authentication对应的TokencopyDetails(authentication, result);break;}}catch (AccountStatusException e) {prepareException(e, authentication);// SEC-546: Avoid polling additional providers if auth failure is due to// invalid account statusthrow e;}catch (InternalAuthenticationServiceException e) {prepareException(e, authentication);throw e;}catch (AuthenticationException e) {lastException = e;}}if (result == null && parent != null) {// Allow the parent to try.try {#5.如果#1 没有验证通过,则使用父类型AuthenticationManager进行验证result = parent.authenticate(authentication);}catch (ProviderNotFoundException e) {// 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 e) {lastException = e;}}#6. 是否擦出敏感信息if (result != null) {if (eraseCredentialsAfterAuthentication&& (result instanceof CredentialsContainer)) {// Authentication is complete. Remove credentials and other secret data// from authentication((CredentialsContainer) result).eraseCredentials();}eventPublisher.publishAuthenticationSuccess(result);return result;}// Parent was null, or didn't authenticate (or throw an exception).if (lastException == null) {lastException = new ProviderNotFoundException(messages.getMessage("ProviderManager.providerNotFound",new Object[] { toTest.getName() },"No AuthenticationProvider found for {0}"));}prepareException(lastException, authentication);throw lastException;}
  1. 遍历所有的 Providers,然后依次执行该 Provider 的验证方法
    • 如果某一个 Provider 验证成功,则跳出循环不再执行后续的验证;
    • 如果验证成功,会将返回的 result 既 Authentication 对象进一步封装为 Authentication Token;
      比如 UsernamePasswordAuthenticationToken、RememberMeAuthenticationToken 等;这些 Authentication Token 也都继承自 Authentication 对象;
  2. 如果 #1 没有任何一个 Provider 验证成功,则试图使用其 parent Authentication Manager 进行验证;
  3. 是否需要擦除密码等敏感信息;

AuthenticationProvider

ProviderManager 通过 AuthenticationProvider 扩展出更多的验证提供的方式;而 AuthenticationProvider 本身也就是一个接口,从类图中我们可以看出它的实现类AbstractUserDetailsAuthenticationProviderAbstractUserDetailsAuthenticationProvider的子类DaoAuthenticationProviderDaoAuthenticationProviderSpring Security中一个核心的Provider,对所有的数据库提供了基本方法和入口。

DaoAuthenticationProvider

DaoAuthenticationProvider主要做了以下事情

  1. 对用户身份尽心加密操作;
     #1.可直接返回BCryptPasswordEncoder,也可以自己实现该接口使用自己的加密算法核心方法String encode(CharSequence rawPassword);和boolean matches(CharSequence rawPassword, String encodedPassword);
    private PasswordEncoder passwordEncoder;
    
  2. 实现了 AbstractUserDetailsAuthenticationProvider 两个抽象方法,

    1. 获取用户信息的扩展点

      protected final UserDetails retrieveUser(String username,UsernamePasswordAuthenticationToken authentication)throws AuthenticationException {UserDetails loadedUser;try {loadedUser = this.getUserDetailsService().loadUserByUsername(username);}
      

      主要是通过注入UserDetailsService接口对象,并调用其接口方法 loadUserByUsername(String username) 获取得到相关的用户信息。UserDetailsService接口非常重要。

    2. 实现 additionalAuthenticationChecks 的验证方法(主要验证密码);

AbstractUserDetailsAuthenticationProvider

AbstractUserDetailsAuthenticationProviderDaoAuthenticationProvider提供了基本的认证方法;

public Authentication authenticate(Authentication authentication)throws AuthenticationException {Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication,messages.getMessage("AbstractUserDetailsAuthenticationProvider.onlySupports","Only UsernamePasswordAuthenticationToken is supported"));// Determine usernameString username = (authentication.getPrincipal() == null) ? "NONE_PROVIDED": authentication.getName();boolean cacheWasUsed = true;UserDetails user = this.userCache.getUserFromCache(username);if (user == null) {cacheWasUsed = false;try {#1.获取用户信息由子类实现即DaoAuthenticationProvideruser = retrieveUser(username,(UsernamePasswordAuthenticationToken) authentication);}catch (UsernameNotFoundException notFound) {logger.debug("User '" + username + "' not found");if (hideUserNotFoundExceptions) {throw new BadCredentialsException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials","Bad credentials"));}else {throw notFound;}}Assert.notNull(user,"retrieveUser returned null - a violation of the interface contract");}try {#2.前检查由DefaultPreAuthenticationChecks类实现(主要判断当前用户是否锁定,过期,冻结User接口)preAuthenticationChecks.check(user);#3.子类实现additionalAuthenticationChecks(user,(UsernamePasswordAuthenticationToken) authentication);}catch (AuthenticationException exception) {if (cacheWasUsed) {// There was a problem, so try again after checking// we're using latest data (i.e. not from the cache)cacheWasUsed = false;user = retrieveUser(username,(UsernamePasswordAuthenticationToken) authentication);preAuthenticationChecks.check(user);additionalAuthenticationChecks(user,(UsernamePasswordAuthenticationToken) authentication);}else {throw exception;}}#4.检测用户密码是否过期对应#2 的User接口postAuthenticationChecks.check(user);if (!cacheWasUsed) {this.userCache.putUserInCache(user);}Object principalToReturn = user;if (forcePrincipalAsString) {principalToReturn = user.getUsername();}return createSuccessAuthentication(principalToReturn, authentication, user);}

AbstractUserDetailsAuthenticationProvider主要实现了AuthenticationProvider的接口方法authenticate 并提供了相关的验证逻辑;

  1. 获取用户返回UserDetails
    AbstractUserDetailsAuthenticationProvider定义了一个抽象的方法
    protected abstract UserDetails retrieveUser(String username,UsernamePasswordAuthenticationToken authentication)throws AuthenticationException;
    
  2. 三步验证工作
    1. preAuthenticationChecks
    2. additionalAuthenticationChecks(抽象方法,子类实现)
    3. postAuthenticationChecks
  3. 将已通过验证的用户信息封装成 UsernamePasswordAuthenticationToken 对象并返回;该对象封装了用户的身份信息,以及相应的权限信息,相关源码如下,

    protected Authentication createSuccessAuthentication(Object principal,UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(principal, authentication.getCredentials(),authoritiesMapper.mapAuthorities(user.getAuthorities()));result.setDetails(authentication.getDetails());return result;}
    

    UserDetailsService

    UserDetailsService是一个接口,提供了一个方法

    public interface UserDetailsService {UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;
    }
    

    通过用户名 username 调用方法 loadUserByUsername 返回了一个UserDetails接口对象(对应AbstractUserDetailsAuthenticationProvider的三步验证方法);

    public interface UserDetails extends Serializable {#1.权限集合Collection<? extends GrantedAuthority> getAuthorities();#2.密码    String getPassword();#3.用户民String getUsername();#4.用户是否过期boolean isAccountNonExpired();#5.是否锁定    boolean isAccountNonLocked();#6.用户密码是否过期    boolean isCredentialsNonExpired();#7.账号是否可用(可理解为是否删除)boolean isEnabled();
    }
    

Spring 为UserDetailsService默认提供了一个实现类 org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl

JdbcUserDetailsManager

该实现类主要是提供基于JDBC对 User 进行增、删、查、改的方法

public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsManager,GroupManager {// ~ Static fields/initializers// =====================================================================================// UserDetailsManager SQL#1.定义了一些列对数据库操作的语句public static final String DEF_CREATE_USER_SQL = "insert into users (username, password, enabled) values (?,?,?)";public static final String DEF_DELETE_USER_SQL = "delete from users where username = ?";public static final String DEF_UPDATE_USER_SQL = "update users set password = ?, enabled = ? where username = ?";public static final String DEF_INSERT_AUTHORITY_SQL = "insert into authorities (username, authority) values (?,?)";public static final String DEF_DELETE_USER_AUTHORITIES_SQL = "delete from authorities where username = ?";public static final String DEF_USER_EXISTS_SQL = "select username from users where username = ?";public static final String DEF_CHANGE_PASSWORD_SQL = "update users set password = ? where username = ?";
InMemoryUserDetailsManager

该实现类主要是提供基于内存对 User 进行增、删、查、改的方法
`public class InMemoryUserDetailsManager implements UserDetailsManager {
protected final Log logger = LogFactory.getLog(getClass());

#1.用MAP 存储
private final Map<String, MutableUserDetails> users = new HashMap<String, MutableUserDetails>();private AuthenticationManager authenticationManager;public InMemoryUserDetailsManager() {
}public InMemoryUserDetailsManager(Collection<UserDetails> users) {for (UserDetails user : users) {createUser(user);}
}`

总结

UserDetailsService接口作为桥梁,是DaoAuthenticationProvier与特定用户信息来源进行解耦的地方,UserDetailsServiceUserDetailsUserDetailsManager所构成;UserDetailsUserDetailsManager各司其责,一个是对基本用户信息进行封装,一个是对基本用户信息进行管理;

特别注意UserDetailsServiceUserDetails以及UserDetailsManager都是可被用户自定义的扩展点,我们可以继承这些接口提供自己的读取用户来源和管理用户的方法,比如我们可以自己实现一个 与特定 ORM 框架,比如 Mybatis 或者 Hibernate,相关的UserDetailsServiceUserDetailsManager

时序图

这篇关于浅析Spring Security认证过程的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1151911

相关文章

Java 实用工具类Spring 的 AnnotationUtils详解

《Java实用工具类Spring的AnnotationUtils详解》Spring框架提供了一个强大的注解工具类org.springframework.core.annotation.Annot... 目录前言一、AnnotationUtils 的常用方法二、常见应用场景三、与 JDK 原生注解 API 的

Java controller接口出入参时间序列化转换操作方法(两种)

《Javacontroller接口出入参时间序列化转换操作方法(两种)》:本文主要介绍Javacontroller接口出入参时间序列化转换操作方法,本文给大家列举两种简单方法,感兴趣的朋友一起看... 目录方式一、使用注解方式二、统一配置场景:在controller编写的接口,在前后端交互过程中一般都会涉及

Java中的StringBuilder之如何高效构建字符串

《Java中的StringBuilder之如何高效构建字符串》本文将深入浅出地介绍StringBuilder的使用方法、性能优势以及相关字符串处理技术,结合代码示例帮助读者更好地理解和应用,希望对大家... 目录关键点什么是 StringBuilder?为什么需要 StringBuilder?如何使用 St

使用Java将各种数据写入Excel表格的操作示例

《使用Java将各种数据写入Excel表格的操作示例》在数据处理与管理领域,Excel凭借其强大的功能和广泛的应用,成为了数据存储与展示的重要工具,在Java开发过程中,常常需要将不同类型的数据,本文... 目录前言安装免费Java库1. 写入文本、或数值到 Excel单元格2. 写入数组到 Excel表格

Java并发编程之如何优雅关闭钩子Shutdown Hook

《Java并发编程之如何优雅关闭钩子ShutdownHook》这篇文章主要为大家详细介绍了Java如何实现优雅关闭钩子ShutdownHook,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起... 目录关闭钩子简介关闭钩子应用场景数据库连接实战演示使用关闭钩子的注意事项开源框架中的关闭钩子机制1.

Maven中引入 springboot 相关依赖的方式(最新推荐)

《Maven中引入springboot相关依赖的方式(最新推荐)》:本文主要介绍Maven中引入springboot相关依赖的方式(最新推荐),本文给大家介绍的非常详细,对大家的学习或工作具有... 目录Maven中引入 springboot 相关依赖的方式1. 不使用版本管理(不推荐)2、使用版本管理(推

Java 中的 @SneakyThrows 注解使用方法(简化异常处理的利与弊)

《Java中的@SneakyThrows注解使用方法(简化异常处理的利与弊)》为了简化异常处理,Lombok提供了一个强大的注解@SneakyThrows,本文将详细介绍@SneakyThro... 目录1. @SneakyThrows 简介 1.1 什么是 Lombok?2. @SneakyThrows

在 Spring Boot 中实现异常处理最佳实践

《在SpringBoot中实现异常处理最佳实践》本文介绍如何在SpringBoot中实现异常处理,涵盖核心概念、实现方法、与先前查询的集成、性能分析、常见问题和最佳实践,感兴趣的朋友一起看看吧... 目录一、Spring Boot 异常处理的背景与核心概念1.1 为什么需要异常处理?1.2 Spring B

如何在 Spring Boot 中实现 FreeMarker 模板

《如何在SpringBoot中实现FreeMarker模板》FreeMarker是一种功能强大、轻量级的模板引擎,用于在Java应用中生成动态文本输出(如HTML、XML、邮件内容等),本文... 目录什么是 FreeMarker 模板?在 Spring Boot 中实现 FreeMarker 模板1. 环

SpringMVC 通过ajax 前后端数据交互的实现方法

《SpringMVC通过ajax前后端数据交互的实现方法》:本文主要介绍SpringMVC通过ajax前后端数据交互的实现方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价... 在前端的开发过程中,经常在html页面通过AJAX进行前后端数据的交互,SpringMVC的controll