SpringSecurity Oauth2 - 密码认证获取访问令牌源码分析

本文主要是介绍SpringSecurity Oauth2 - 密码认证获取访问令牌源码分析,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文章目录

    • 1. 授权服务器过滤器
      • 1. 常用的过滤器
      • 2. 工作原理
    • 2. 密码模式获取访问令牌
      • 1. 工作流程
      • 2. 用户凭证验证
        • 1. ResourceOwnerPasswordTokenGranter
        • 2. ProviderManager
        • 3. CustomAuthProvider
        • 4. 认证后的结果

1. 授权服务器过滤器

在Spring Security中,OAuth2授权服务器的过滤器是处理OAuth2授权流程的核心组件之一。它们在请求进入授权服务器时被应用,以确保请求的合法性,并执行授权和令牌处理。

1. 常用的过滤器

AuthorizationEndpointFilter:

  • 处理/oauth/authorize请求,它是OAuth2授权流程的核心过滤器。
  • 负责处理客户端请求授权码或访问令牌的过程。这个过滤器会检查请求的有效性、处理用户的认证信息、并将请求引导至授权页面(通常是一个登录页面或授权确认页面)。

TokenEndpointFilter:

  • 处理/oauth/token请求,这是获取访问令牌和刷新令牌的核心过滤器。
  • 负责处理各种授权方式的令牌颁发过程,包括授权码模式、密码模式、客户端凭据模式等。

ClientCredentialsTokenEndpointFilter:

  • 专门处理客户端凭据授权模式的令牌请求。
  • 负责验证客户端的身份并直接发放访问令牌,因为客户端凭据模式不涉及用户的授权确认。

CheckTokenEndpointFilter:

  • 处理令牌的检查请求,通常位于/oauth/check_token路径下。
  • 用于验证令牌的有效性,通常是资源服务器用来验证访问令牌是否有效的一个过滤器。

OAuth2LoginAuthenticationFilter:

  • 处理OAuth2登录流程,处理授权码登录或隐式授权流程中的登录请求。
  • 这个过滤器在接收到OAuth2的登录请求后,执行OAuth2的认证流程,并在认证成功后生成相应的OAuth2授权信息。

2. 工作原理

① 过滤器链:在Spring Security的配置中,这些过滤器通常被配置在一个过滤器链中,这样每个请求都会经过这些过滤器,并根据请求路径、请求参数和方法来决定该请求需要经过哪些过滤器的处理。

② 安全配置:Spring Security OAuth2的配置通过AuthorizationServerConfigurerAdapter类来进行。在这个类中,你可以配置上述的过滤器,并指定授权路径、令牌路径、客户端详细信息服务、以及各种授权方式的处理逻辑。

③ 令牌存储:这些过滤器通常会结合令牌存储(例如内存存储、数据库存储或JWT存储)一起使用,以管理访问令牌和刷新令牌的生成、存储、验证和撤销。

2. 密码模式获取访问令牌

1. 工作流程

在这里插入图片描述

① 验证客户端:首先,TokenEndpointFilter 会调用 ClientCredentialsTokenEndpointFilter 验证 client_idclient_secret,确保客户端的合法性。

② 用户凭证验证:如果客户端验证通过,ResourceOwnerPasswordTokenGranter 会验证 usernamepassword。如果用户凭证正确,则生成访问令牌。

③ 生成和返回令牌:如果所有验证通过,过滤器会生成访问令牌并返回给客户端。

这套流程确保了在密码模式下,只有正确的客户端和用户组合才能成功获取访问令牌。

2. 用户凭证验证

1. ResourceOwnerPasswordTokenGranter
public class ResourceOwnerPasswordTokenGranter extends AbstractTokenGranter {private static final String GRANT_TYPE = "password";private final AuthenticationManager authenticationManager;public ResourceOwnerPasswordTokenGranter(AuthenticationManager authenticationManager,AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory) {this(authenticationManager, tokenServices, clientDetailsService, requestFactory, GRANT_TYPE);}protected ResourceOwnerPasswordTokenGranter(AuthenticationManager authenticationManager, AuthorizationServerTokenServices tokenServices,ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory, String grantType) {super(tokenServices, clientDetailsService, requestFactory, grantType);this.authenticationManager = authenticationManager;}@Overrideprotected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {Map<String, String> parameters = new LinkedHashMap<String, String>(tokenRequest.getRequestParameters());String username = parameters.get("username");String password = parameters.get("password");// Protect from downstream leaks of passwordparameters.remove("password");Authentication userAuth = new UsernamePasswordAuthenticationToken(username, password);((AbstractAuthenticationToken) userAuth).setDetails(parameters);try {userAuth = authenticationManager.authenticate(userAuth);}catch (AccountStatusException ase) {//covers expired, locked, disabled cases (mentioned in section 5.2, draft 31)throw new InvalidGrantException(ase.getMessage());}catch (BadCredentialsException e) {// If the username/password are wrong the spec says we should send 400/invalid grantthrow new InvalidGrantException(e.getMessage());}if (userAuth == null || !userAuth.isAuthenticated()) {throw new InvalidGrantException("Could not authenticate user: " + username);}OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);		return new OAuth2Authentication(storedOAuth2Request, userAuth);}
}

在这里插入图片描述

2. ProviderManager
public class ProviderManager implements AuthenticationManager, MessageSourceAware,InitializingBean {private static final Log logger = LogFactory.getLog(ProviderManager.class);private AuthenticationEventPublisher eventPublisher = new NullEventPublisher();private List<AuthenticationProvider> providers = Collections.emptyList();protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();private AuthenticationManager parent;private boolean eraseCredentialsAfterAuthentication = true;public ProviderManager(List<AuthenticationProvider> providers) {this(providers, null);}public ProviderManager(List<AuthenticationProvider> providers,AuthenticationManager parent) {Assert.notNull(providers, "providers list cannot be null");this.providers = providers;this.parent = parent;checkState();}public void afterPropertiesSet() {checkState();}private void checkState() {if (parent == null && providers.isEmpty()) {throw new IllegalArgumentException("A parent AuthenticationManager or a list "+ "of AuthenticationProviders is required");}}public Authentication authenticate(Authentication authentication)throws AuthenticationException {Class<? extends Authentication> toTest = authentication.getClass();AuthenticationException lastException = null;AuthenticationException parentException = null;Authentication result = null;Authentication parentResult = null;boolean debug = logger.isDebugEnabled();for (AuthenticationProvider provider : getProviders()) {if (!provider.supports(toTest)) {continue;}if (debug) {logger.debug("Authentication attempt using "+ provider.getClass().getName());}try {result = provider.authenticate(authentication);if (result != null) {copyDetails(authentication, result);break;}}catch (AccountStatusException | InternalAuthenticationServiceException e) {prepareException(e, authentication);// SEC-546: Avoid polling additional providers if auth failure is due to// invalid account statusthrow e;} catch (AuthenticationException e) {lastException = e;}}if (result == null && parent != null) {// Allow the parent to try.try {result = parentResult = 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 = parentException = e;}}if (result != null) {if (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 than it will publish an AuthenticationSuccessEvent// This check prevents a duplicate AuthenticationSuccessEvent if the parent AuthenticationManager already published itif (parentResult == null) {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}"));}// If the parent AuthenticationManager was attempted and failed than it will publish an AbstractAuthenticationFailureEvent// This check prevents a duplicate AbstractAuthenticationFailureEvent if the parent AuthenticationManager already published itif (parentException == null) {prepareException(lastException, authentication);}throw lastException;}@SuppressWarnings("deprecation")private void prepareException(AuthenticationException ex, Authentication auth) {eventPublisher.publishAuthenticationFailure(ex, auth);}/*** Copies the authentication details from a source Authentication object to a* destination one, provided the latter does not already have one set.** @param source source authentication* @param dest the destination authentication object*/private void copyDetails(Authentication source, Authentication dest) {if ((dest instanceof AbstractAuthenticationToken) && (dest.getDetails() == null)) {AbstractAuthenticationToken token = (AbstractAuthenticationToken) dest;token.setDetails(source.getDetails());}}public List<AuthenticationProvider> getProviders() {return providers;}public void setMessageSource(MessageSource messageSource) {this.messages = new MessageSourceAccessor(messageSource);}public void setAuthenticationEventPublisher(AuthenticationEventPublisher eventPublisher) {Assert.notNull(eventPublisher, "AuthenticationEventPublisher cannot be null");this.eventPublisher = eventPublisher;}public void setEraseCredentialsAfterAuthentication(boolean eraseSecretData) {this.eraseCredentialsAfterAuthentication = eraseSecretData;}public boolean isEraseCredentialsAfterAuthentication() {return eraseCredentialsAfterAuthentication;}private static final class NullEventPublisher implements AuthenticationEventPublisher {public void publishAuthenticationFailure(AuthenticationException exception,Authentication authentication) {}public void publishAuthenticationSuccess(Authentication authentication) {}}
}

在这里插入图片描述

3. CustomAuthProvider
@Component
public class CustomAuthProvider implements AuthenticationProvider {@Autowiredprivate CustomUserDetailService userDetailService;@Overridepublic Authentication authenticate(Authentication authentication) throws AuthenticationException {String username = authentication.getName();String password = (String) authentication.getCredentials();UserDetails userDetails = userDetailService.loadUserByUsername(username);UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken= new UsernamePasswordAuthenticationToken(username, password, userDetails.getAuthorities());usernamePasswordAuthenticationToken.setDetails(authentication.getDetails());return usernamePasswordAuthenticationToken;}@Overridepublic boolean supports(Class<?> authentication) {return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);}
}

在这里插入图片描述

4. 认证后的结果

在这里插入图片描述

这篇关于SpringSecurity Oauth2 - 密码认证获取访问令牌源码分析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

Spring boot整合dubbo+zookeeper的详细过程

《Springboot整合dubbo+zookeeper的详细过程》本文讲解SpringBoot整合Dubbo与Zookeeper实现API、Provider、Consumer模式,包含依赖配置、... 目录Spring boot整合dubbo+zookeeper1.创建父工程2.父工程引入依赖3.创建ap

SpringBoot结合Docker进行容器化处理指南

《SpringBoot结合Docker进行容器化处理指南》在当今快速发展的软件工程领域,SpringBoot和Docker已经成为现代Java开发者的必备工具,本文将深入讲解如何将一个SpringBo... 目录前言一、为什么选择 Spring Bootjavascript + docker1. 快速部署与

MySQL中的LENGTH()函数用法详解与实例分析

《MySQL中的LENGTH()函数用法详解与实例分析》MySQLLENGTH()函数用于计算字符串的字节长度,区别于CHAR_LENGTH()的字符长度,适用于多字节字符集(如UTF-8)的数据验证... 目录1. LENGTH()函数的基本语法2. LENGTH()函数的返回值2.1 示例1:计算字符串

Spring Boot spring-boot-maven-plugin 参数配置详解(最新推荐)

《SpringBootspring-boot-maven-plugin参数配置详解(最新推荐)》文章介绍了SpringBootMaven插件的5个核心目标(repackage、run、start... 目录一 spring-boot-maven-plugin 插件的5个Goals二 应用场景1 重新打包应用

SpringBoot+EasyExcel实现自定义复杂样式导入导出

《SpringBoot+EasyExcel实现自定义复杂样式导入导出》这篇文章主要为大家详细介绍了SpringBoot如何结果EasyExcel实现自定义复杂样式导入导出功能,文中的示例代码讲解详细,... 目录安装处理自定义导出复杂场景1、列不固定,动态列2、动态下拉3、自定义锁定行/列,添加密码4、合并

Spring Boot集成Druid实现数据源管理与监控的详细步骤

《SpringBoot集成Druid实现数据源管理与监控的详细步骤》本文介绍如何在SpringBoot项目中集成Druid数据库连接池,包括环境搭建、Maven依赖配置、SpringBoot配置文件... 目录1. 引言1.1 环境准备1.2 Druid介绍2. 配置Druid连接池3. 查看Druid监控

Java中读取YAML文件配置信息常见问题及解决方法

《Java中读取YAML文件配置信息常见问题及解决方法》:本文主要介绍Java中读取YAML文件配置信息常见问题及解决方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要... 目录1 使用Spring Boot的@ConfigurationProperties2. 使用@Valu

创建Java keystore文件的完整指南及详细步骤

《创建Javakeystore文件的完整指南及详细步骤》本文详解Java中keystore的创建与配置,涵盖私钥管理、自签名与CA证书生成、SSL/TLS应用,强调安全存储及验证机制,确保通信加密和... 目录1. 秘密键(私钥)的理解与管理私钥的定义与重要性私钥的管理策略私钥的生成与存储2. 证书的创建与

浅析Spring如何控制Bean的加载顺序

《浅析Spring如何控制Bean的加载顺序》在大多数情况下,我们不需要手动控制Bean的加载顺序,因为Spring的IoC容器足够智能,但在某些特殊场景下,这种隐式的依赖关系可能不存在,下面我们就来... 目录核心原则:依赖驱动加载手动控制 Bean 加载顺序的方法方法 1:使用@DependsOn(最直

SpringBoot中如何使用Assert进行断言校验

《SpringBoot中如何使用Assert进行断言校验》Java提供了内置的assert机制,而Spring框架也提供了更强大的Assert工具类来帮助开发者进行参数校验和状态检查,下... 目录前言一、Java 原生assert简介1.1 使用方式1.2 示例代码1.3 优缺点分析二、Spring Fr