首页 > 其他分享 >自定义 Spring Authorization Server 配置

自定义 Spring Authorization Server 配置

时间:2022-11-10 10:33:21浏览次数:67  
标签:OAuth2 自定义 Spring 配置 OAuth2AuthorizationServerConfigurer 端点 Authorization 客户端

Spring OAuthorization Server 自定义配置非常重要,后面的所有定制配置都是基于此。本文先介绍 OAuth2AuthorizationServerConfigurer 提供的配置选项,并使用 Provider Settings 和 Client Authentication 作为例子。

OAuth2AuthorizationServerConfigurer 提供了为 OAuth2 授权服务器完全自定义安全配置的能力。它允许您指定要使用的核心组件——例如,RegisteredClientRepositoryOAuth2AuthorizationServiceOAuth2TokenGenerator等。此外,它还允许为协议端点自定义请求处理逻辑——例如,授权端点、token 端点、token 内省端点等。

OAuth2AuthorizationServerConfigurer 提供以下配置选项:

@Bean
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
	OAuth2AuthorizationServerConfigurer<HttpSecurity> authorizationServerConfigurer =
		new OAuth2AuthorizationServerConfigurer<>();
	http.apply(authorizationServerConfigurer);

	authorizationServerConfigurer
        // 用于管理新的和现有的客户端。
		.registeredClientRepository(registeredClientRepository) 
        // 用于管理新的和现有的授权。
		.authorizationService(authorizationService) 
        // 用于管理新的和现有的授权许可。
		.authorizationConsentService(authorizationConsentService)
        // 用于自定义 OAuth2 授权服务器的配置设置。
		.providerSettings(providerSettings) 
        // 用于生成 OAuth2 授权服务器支持的令牌。
		.tokenGenerator(tokenGenerator) 
        // OAuth2 客户端身份认证的配置器。
		.clientAuthentication(clientAuthentication -> { })  
        // OAuth2 授权端点的配置器。
		.authorizationEndpoint(authorizationEndpoint -> { })    
        // OAuth2 token 端点的配置器。
		.tokenEndpoint(tokenEndpoint -> { })    
        // OAuth2 token 内省端点的配置器。
		.tokenIntrospectionEndpoint(tokenIntrospectionEndpoint -> { })  
        // OAuth2 token 撤销端点的配置器。
		.tokenRevocationEndpoint(tokenRevocationEndpoint -> { })    
		.oidc(oidc -> oidc
             // OpenID Connect 1.0 UserInfo 端点的配置器。
			.userInfoEndpoint(userInfoEndpoint -> { })  
             // OpenID Connect 1.0 客户端注册端点的配置器。
			.clientRegistrationEndpoint(clientRegistrationEndpoint -> { })  
		);

	return http.build();
}

配置 Provider Settings

ProviderSettings 包含 OAuth2 授权服务器的配置设置。它指定协议端点的 URI 以及发行者(issuer)。协议端点的默认 URI 如下:

public final class ProviderSettings extends AbstractSettings {

	...

	public static Builder builder() {
		return new Builder()
			.authorizationEndpoint("/oauth2/authorize")
			.tokenEndpoint("/oauth2/token")
			.tokenIntrospectionEndpoint("/oauth2/introspect")
			.tokenRevocationEndpoint("/oauth2/revoke")
			.jwkSetEndpoint("/oauth2/jwks")
			.oidcUserInfoEndpoint("/userinfo")
			.oidcClientRegistrationEndpoint("/connect/register");
	}

	...

}

下面的例子展示了如何自定义配置设置并注册到 bean 容器中:

@Bean
public ProviderSettings providerSettings() {
	return ProviderSettings.builder()
		.issuer("https://example.com")
		.authorizationEndpoint("/oauth2/v1/authorize")
		.tokenEndpoint("/oauth2/v1/token")
		.tokenIntrospectionEndpoint("/oauth2/v1/introspect")
		.tokenRevocationEndpoint("/oauth2/v1/revoke")
		.jwkSetEndpoint("/oauth2/v1/jwks")
		.oidcUserInfoEndpoint("/connect/v1/userinfo")
		.oidcClientRegistrationEndpoint("/connect/v1/register")
		.build();
}

ProviderContext 是一个上下文对象,它保存有关 provider 的信息。它提供对 ProviderSettings 和“当前”颁发者(issuer)的访问。ProviderContext 可以通过 ProviderContextHolder 获取,后者通过使用 ThreadLocal 将其与当前请求线程关联起来。


除了将 ProviderSettings 注册到 bean 容器中,还可以通过上面提到的 OAuth2AuthorizationServerConfigurer配置:

@Bean
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
	OAuth2AuthorizationServerConfigurer<HttpSecurity> authorizationServerConfigurer =
		new OAuth2AuthorizationServerConfigurer<>();
	http.apply(authorizationServerConfigurer);

	authorizationServerConfigurer
        ...
        // 用于自定义 OAuth2 授权服务器的配置设置。
		.providerSettings(providerSettings) 
        
        ...;

	return http.build();
}

配置 Client Authentication

OAuth2AuthorizationServerConfigurer 提供自定义 OAuth2 客户端身份认证的能力。它定义了扩展点,允许您为客户端身份认证请求自定义预处理、主处理和后处理逻辑。

OAuth2AuthorizationServerConfigurer 提供以下配置选项:

@Bean
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
	OAuth2AuthorizationServerConfigurer<HttpSecurity> authorizationServerConfigurer =
		new OAuth2AuthorizationServerConfigurer<>();
	http.apply(authorizationServerConfigurer);

	authorizationServerConfigurer
		.clientAuthentication(clientAuthentication ->
			clientAuthentication
                // 尝试从 HttpServletRequest 提取客户端凭证到 OAuth2ClientAuthenticationToken 实例时使用的 AuthenticationConverter(预处理器)。
				.authenticationConverter(authenticationConverter)   
                // 用于对 OAuth2ClientAuthenticationToken 进行身份验证的 AuthenticationProvider(主处理器)。(可以添加一个或多个替换默认值。)
				.authenticationProvider(authenticationProvider) 
                // AuthenticationSuccessHandler(后处理器)用于处理成功的客户端身份验证并将 OAuth2ClientAuthenticationToken 关联到SecurityContext。
				.authenticationSuccessHandler(authenticationSuccessHandler) 
                // AuthenticationFailureHandler(后处理器),用于处理客户端身份验证失败并返回 OAuth2Error 响应。
				.errorResponseHandler(errorResponseHandler) 
		);

	return http.build();
}

OAuth2AuthorizationServerConfigurer 配置了 OAuth2ClientAuthenticationFilter,并将其注册到 OAuth2 授权服务器 SecurityFilterChain 中。OAuth2ClientAuthenticationFilter 是处理客户端身份验证请求的过滤器。

默认情况下,OAuth2 token 端点、OAuth2 token 内省端点和 OAuth2 token 撤销端点需要进行客户端身份认证。支持的客户端身份认证方法有client_secret_basicclient_secret_postprivate_key_jwtclient_secret_jwtnone(公共客户端)。

OAuth2ClientAuthenticationFilter 配置了以下默认值:

  • AuthenticationConverter — 一个由 JwtClientAssertionAuthenticationConverterClientSecretBasicAuthenticationConverterClientSecretPostAuthenticationConverterPublicClientAuthenticationConverter 组成的 DelegatingAuthenticationConverter
  • AuthenticationManager — 由 JwtClientAssertionAuthenticationProviderClientSecretAuthenticationProviderPublicClientAuthenticationProvider 组成的 AuthenticationManager
  • AuthenticationSuccessHandler — 将“已认证”的 OAuth2ClientAuthenticationToken (当前的 Authentication)与 SecurityContext 关联的内部实现。
  • AuthenticationFailureHandler — 使用与 OAuth2AuthenticationException 关联的 OAuth2Error 返回 OAuth2 错误响应的内部实现。

项目实战

Spring Authorization Server 实战项目:

Gitee GitHub
后端 https://gitee.com/linjiabin100/pi-cloud.git https://github.com/zengpi/pi-cloud.git
前端 https://gitee.com/linjiabin100/pi-cloud-web.git https://github.com/zengpi/pi-cloud-web.git

标签:OAuth2,自定义,Spring,配置,OAuth2AuthorizationServerConfigurer,端点,Authorization,客户端
From: https://www.cnblogs.com/zn-pi/p/16876272.html

相关文章

  • SpringCloud(九) - Nginx
    1、安装Nginx1.1解压上传安装包解压#nginx-1.16.1.tar.gz#nginx需要一些环境(全部执行,不存在的会执行,存在的会跳过)yuminstall-ywgetyuminstall-ygcc-c++......
  • 基于Docker部署Springboot工程
    主要参考文章:https://blog.csdn.net/qq_33285112/article/details/109726538https://www.cnblogs.com/linnuo/p/15699121.html一、首先基于Alpine构建Java最小运行环境......
  • springboot文件上传大小限制设置
    一般的web系统基本都会有文件上传功能,文件上传必然涉及到一个问题,就是文件大小,太大的文件不仅传输速度慢,而且对服务器压力巨大,后期的下载和保存都是一种考验。所以有了文......
  • Spring Security 知识点总结
    Security部分WebSecurityConfigurerAdaptersecurity配置的核心类在这里配置权限等信息authenticationauthentication是认证(登陆)authorizationauthorizati......
  • Spring Security 知识点总结
    Security部分WebSecurityConfigurerAdaptersecurity配置的核心类在这里配置权限等信息authenticationauthentication是认证(登陆)authorizationauthorizati......
  • Spring Boot 中使用 tkMapper
    说明:基于MyBatis有很多第三方功能插件,这些插件可以完成数据操作方法的封装、数据库逆向工程的生成等。tkMapper和MyBatis-plus都是基于MyBatis提供的第三方插件,功......
  • 自定义centos
    1修改rootfs.img1.安装工具[root@localhost~]#yuminstall-ysquashfs-tools2.用unsuqashfs命令直接解压缩squashfs.img[root@localhost~]#unsquashfssquashfs.img3......
  • 01-SpringBoot注解
    SpringBoot注解Spring常用注解配置注解含义@Configuration定义一个类是Spring配置类@Bean配置自定义的Bean,如DruidDataSource@Componen......
  • Spring Cloud 之Config配置中心-使用Bus组件实现配置动态更新
    推荐:微服务汇总SpringCloud之Config配置中心-使用Bus组件实现配置动态更新首先创建一个SpringBoot项目作为注册中心。pom.xml如下:<?xmlversion="1.0"encoding="U......
  • Spring Boot:文件下载
    测试代码​​pom.xml​​:<?xmlversion="1.0"encoding="UTF-8"?><projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-inst......