授权许可(Authorization Grant)的支持

本站(springdoc.cn)中的内容来源于 spring.io ,原始版权归属于 spring.io。由 springdoc.cn 进行翻译,整理。可供个人学习、研究,未经许可,不得进行任何转载、商用或与之相关的行为。 商标声明:Spring 是 Pivotal Software, Inc. 在美国以及其他国家的商标。

Authorization Code(授权代码)

关于 Authorization Code 授予的进一步细节,请参考OAuth 2.0授权框架。

获取授权

请参考授权代码授予的 授权请求/响应 协议流程。

发起授权请求

OAuth2AuthorizationRequestRedirectWebFilter 使用 ServerOAuth2AuthorizationRequestResolver 来解决 OAuth2AuthorizationRequest,并通过将终端用户的用户代理重定向到授权服务器的授权端点来启动授权代码授予流程。

ServerOAuth2AuthorizationRequestResolver 的主要作用是从提供的Web请求中解析 OAuth2AuthorizationRequest。默认的实现 DefaultServerOAuth2AuthorizationRequestResolver 在(默认)路径 /oauth2/authorization/{registrationId} 上进行匹配,提取 registrationId 并使用它来建立相关 ClientRegistrationOAuth2AuthorizationRequest

给出以下Spring Boot 2.x属性,用于OAuth 2.0客户端注册。

spring:
  security:
    oauth2:
      client:
        registration:
          okta:
            client-id: okta-client-id
            client-secret: okta-client-secret
            authorization-grant-type: authorization_code
            redirect-uri: "{baseUrl}/authorized/okta"
            scope: read, write
        provider:
          okta:
            authorization-uri: https://dev-1234.oktapreview.com/oauth2/v1/authorize
            token-uri: https://dev-1234.oktapreview.com/oauth2/v1/token

一个基本路径为 /oauth2/authorization/okta 的请求将启动 OAuth2AuthorizationRequestRedirectWebFilter 的授权请求重定向,并最终启动授权代码授予流程。

AuthorizationCodeReactiveOAuth2AuthorizedClientProviderReactiveOAuth2AuthorizedClientProvider 的一个实现,用于授权码的授予,它也启动了 OAuth2AuthorizationRequestRedirectWebFilter 的授权请求重定向。

如果 OAuth 2.0 客户端是一个 公共客户端,那么请按以下方式配置OAuth 2.0客户端的注册。

spring:
  security:
    oauth2:
      client:
        registration:
          okta:
            client-id: okta-client-id
            client-authentication-method: none
            authorization-grant-type: authorization_code
            redirect-uri: "{baseUrl}/authorized/okta"
            ...

公共客户端支持使用 代码交换的证明密钥(PKCE)。如果客户端运行在一个不受信任的环境中(例如,本地应用程序或基于Web浏览器的应用程序),因此没有能力维护其证书的机密性,当以下条件为真时,PKCE将自动被使用。

  1. client-secret 省略(或为空)。

  2. client-authentication-method 被设置为 "none" (ClientAuthenticationMethod.NONE)

如果OAuth 2.0提供商支持 Confidential Client,你可以(选择性地)使用 DefaultServerOAuth2AuthorizationRequestResolver.setAuthorizationRequestCustomizer(OAuth2AuthorizationRequestCustomizers.withPkce()) 来配置它。

DefaultServerOAuth2AuthorizationRequestResolver 还支持使用 UriComponentsBuilderURI 模板变量用于 redirect-uri

下面的配置使用了所有支持的 URI 模板变量。

spring:
  security:
    oauth2:
      client:
        registration:
          okta:
            ...
            redirect-uri: "{baseScheme}://{baseHost}{basePort}{basePath}/authorized/{registrationId}"
            ...
{baseUrl} 解析为 {baseScheme}://{baseHost}{basePort}{basePath}

当OAuth 2.0客户端在 代理服务器(Proxy Server) 后面运行时,用 URI 模板变量配置 redirect-uri 特别有用。这可以确保在扩展 redirect-uri 时使用 X-Forwarded-* 头信息。

自定义授权请求

ServerOAuth2AuthorizationRequestResolver 可以实现的一个主要用例是,在OAuth 2.0授权框架中定义的标准参数之上,用额外的参数来定制授权请求的能力。

例如,OpenID Connect为 授权代码流 定义了额外的OAuth 2.0请求参数,这些参数是从 OAuth 2.0授权框架 中定义的标准参数延伸出来的。其中一个扩展参数是 prompt 参数。

可选的。以空格分隔、区分大小写的 ASCII 字符串值列表,指定授权服务器是否提示终端用户重新认证和同意。定义的值是:none、login、consent、select_account

下面的例子显示了如何配置 DefaultServerOAuth2AuthorizationRequestResolver 与一个 Consumer<OAuth2AuthorizationRequest.Builder>,通过包括请求参数 prompt=consent,定制 oauth2Login() 的授权请求。

  • Java

  • Kotlin

@Configuration
@EnableWebFluxSecurity
public class OAuth2LoginSecurityConfig {

	@Autowired
	private ReactiveClientRegistrationRepository clientRegistrationRepository;

	@Bean
	public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
		http
			.authorizeExchange(authorize -> authorize
				.anyExchange().authenticated()
			)
			.oauth2Login(oauth2 -> oauth2
				.authorizationRequestResolver(
					authorizationRequestResolver(this.clientRegistrationRepository)
				)
			);
		return http.build();
	}

	private ServerOAuth2AuthorizationRequestResolver authorizationRequestResolver(
			ReactiveClientRegistrationRepository clientRegistrationRepository) {

		DefaultServerOAuth2AuthorizationRequestResolver authorizationRequestResolver =
				new DefaultServerOAuth2AuthorizationRequestResolver(
						clientRegistrationRepository);
		authorizationRequestResolver.setAuthorizationRequestCustomizer(
				authorizationRequestCustomizer());

		return  authorizationRequestResolver;
	}

	private Consumer<OAuth2AuthorizationRequest.Builder> authorizationRequestCustomizer() {
		return customizer -> customizer
					.additionalParameters(params -> params.put("prompt", "consent"));
	}
}
@Configuration
@EnableWebFluxSecurity
class SecurityConfig {

    @Autowired
    private lateinit var customClientRegistrationRepository: ReactiveClientRegistrationRepository

    @Bean
    fun securityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
        http {
            authorizeExchange {
                authorize(anyExchange, authenticated)
            }
            oauth2Login {
                authorizationRequestResolver = authorizationRequestResolver(customClientRegistrationRepository)
            }
        }

        return http.build()
    }

    private fun authorizationRequestResolver(
            clientRegistrationRepository: ReactiveClientRegistrationRepository): ServerOAuth2AuthorizationRequestResolver {
        val authorizationRequestResolver = DefaultServerOAuth2AuthorizationRequestResolver(
                clientRegistrationRepository)
        authorizationRequestResolver.setAuthorizationRequestCustomizer(
                authorizationRequestCustomizer())
        return authorizationRequestResolver
    }

    private fun authorizationRequestCustomizer(): Consumer<OAuth2AuthorizationRequest.Builder> {
        return Consumer { customizer ->
            customizer
                .additionalParameters { params -> params["prompt"] = "consent" }
        }
    }
}

对于简单的用例,即额外的请求参数对于特定的提供者总是相同的,它可以直接添加到 authorization-uri 属性中。

例如,如果请求参数 prompt 对提供者 okta 来说总是 consent,那么只需按以下方式配置。

spring:
  security:
    oauth2:
      client:
        provider:
          okta:
            authorization-uri: https://dev-1234.oktapreview.com/oauth2/v1/authorize?prompt=consent

前面的例子显示了在标准参数之上添加自定义参数的常见使用情况。另外,如果你的要求更高级,你可以通过简单地覆盖 OAuth2AuthorizationRequest.authorizationRequestUri 属性来完全控制构建授权请求URI。

OAuth2AuthorizationRequest.Builder.build() 构建了 OAuth2AuthorizationRequest.authorizationRequestUri,它表示授权请求URI,包括使用 application/x-www-form-urlencoded 格式的所有查询参数。

下面的例子显示了前述例子中 authorizationRequestCustomizer() 的一个变化,而是重写了 OAuth2AuthorizationRequest.authorizationRequestUri 属性。

  • Java

  • Kotlin

private Consumer<OAuth2AuthorizationRequest.Builder> authorizationRequestCustomizer() {
	return customizer -> customizer
			.authorizationRequestUri(uriBuilder -> uriBuilder
					.queryParam("prompt", "consent").build());
}
private fun authorizationRequestCustomizer(): Consumer<OAuth2AuthorizationRequest.Builder> {
    return Consumer { customizer: OAuth2AuthorizationRequest.Builder ->
        customizer
                .authorizationRequestUri { uriBuilder: UriBuilder ->
                    uriBuilder
                            .queryParam("prompt", "consent").build()
                }
    }
}

储存授权请求

ServerAuthorizationRequestRepository 负责 OAuth2AuthorizationRequest 的持久化,从发起授权请求到收到授权响应(回调)的过程。

OAuth2AuthorizationRequest 是用来关联和验证授权响应的。

ServerAuthorizationRequestRepository 的默认实现是 WebSessionOAuth2ServerAuthorizationRequestRepository,它将 OAuth2AuthorizationRequest 存储在 WebSession 中。

如果你有一个自定义的 ServerAuthorizationRequestRepository 的实现,你可以按照下面的例子来配置它。

ServerAuthorizationRequestRepository Configuration
  • Java

  • Kotlin

@Configuration
@EnableWebFluxSecurity
public class OAuth2ClientSecurityConfig {

	@Bean
	public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
		http
			.oauth2Client(oauth2 -> oauth2
				.authorizationRequestRepository(this.authorizationRequestRepository())
				...
			);
		return http.build();
	}
}
@Configuration
@EnableWebFluxSecurity
class OAuth2ClientSecurityConfig {

    @Bean
    fun securityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
        http {
            oauth2Client {
                authorizationRequestRepository = authorizationRequestRepository()
            }
        }

        return http.build()
    }
}

请求 Access Token

请参考 访问令牌请求/响应 协议流程中的授权码授予。

授权码授予的 ReactiveOAuth2AccessTokenResponseClient 的默认实现是 WebClientReactiveAuthorizationCodeTokenResponseClient,它使用 WebClient 在授权服务器的Token端点交换授权码的访问令牌。

WebClientReactiveAuthorizationCodeTokenResponseClient 是相当灵活的,因为它允许你定制令牌请求的预处理(pre-processing)和/或令牌响应的后处理(post-handling)。

自定义 Access Token 请求

如果你需要定制令牌请求的预处理,你可以为 WebClientReactiveAuthorizationCodeTokenResponseClient.setParametersConverter() 提供一个自定义的 Converter<OAuth2AuthorizationCodeGrantRequest, MultiValueMap<String, String>>。默认的实现建立了一个 MultiValueMap<String, String>,只包含标准 OAuth 2.0访问令牌请求grant_type 参数,用于构建请求。授权码授予所需的其他参数是由 WebClientReactiveAuthorizationCodeTokenResponseClient 直接添加到请求 body 中的。然而,提供一个自定义的 Converter,将允许你扩展标准的令牌(Token)请求并添加自定义参数。

如果你喜欢只添加额外的参数,你可以改为向 WebClientReactiveAuthorizationCodeTokenResponseClient.addParametersConverter() 提供一个自定义的 Converter<OAuth2AuthorizationCodeGrantRequest, MultiValueMap<String, String>>,构建一个聚合的 Converter
自定义 Converter 必须返回OAuth 2.0访问令牌请求的有效参数,并能被预定的OAuth 2.0提供商理解。

自定义 Access Token 响应

在另一端,如果你需要定制令牌响应的后期处理,你需要为 WebClientReactiveAuthorizationCodeTokenResponseClient.setBodyExtractor() 提供一个自定义配置的 BodyExtractor<Mono<OAuth2AccessTokenResponse>, ReactiveHttpInputMessage>,用于将 OAuth2.0 访问令牌响应转换为 OAuth2AccessTokenResponseOAuth2BodyExtractors.oauth2AccessTokenResponse() 提供的默认实现会解析响应并相应地处理错误。

自定义 WebClient

另外,如果你的要求更高级,你可以通过简单地提供 WebClientReactiveAuthorizationCodeTokenResponseClient.setWebClient() 与一个自定义配置的 WebClient 来完全控制请求/响应。

无论你是定制 WebClientReactiveAuthorizationCodeTokenResponseClient 还是提供你自己的 ReactiveOAuth2AccessTokenResponseClient 的实现,你都需要按照下面的例子来配置它。

Access Token Response Configuration
  • Java

  • Kotlin

@Configuration
@EnableWebFluxSecurity
public class OAuth2ClientSecurityConfig {

	@Bean
	public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
		http
			.oauth2Client(oauth2 -> oauth2
				.authenticationManager(this.authorizationCodeAuthenticationManager())
				...
			);
		return http.build();
	}

	private ReactiveAuthenticationManager authorizationCodeAuthenticationManager() {
		WebClientReactiveAuthorizationCodeTokenResponseClient accessTokenResponseClient =
				new WebClientReactiveAuthorizationCodeTokenResponseClient();
		...

		return new OAuth2AuthorizationCodeReactiveAuthenticationManager(accessTokenResponseClient);
	}
}
@Configuration
@EnableWebFluxSecurity
class OAuth2ClientSecurityConfig {

    @Bean
    fun securityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
        http {
            oauth2Client {
                authenticationManager = authorizationCodeAuthenticationManager()
            }
        }

        return http.build()
    }

    private fun authorizationCodeAuthenticationManager(): ReactiveAuthenticationManager {
        val accessTokenResponseClient = WebClientReactiveAuthorizationCodeTokenResponseClient()
        ...

        return OAuth2AuthorizationCodeReactiveAuthenticationManager(accessTokenResponseClient)
    }
}

刷新 Token

关于 刷新令牌 的更多细节,请参考OAuth 2.0授权框架。

刷新 Access Token

请参考 Access Token 请求/响应 协议流程,了解刷新令牌 grant。

刷新令牌授予的 ReactiveOAuth2AccessTokenResponseClient 的默认实现是 WebClientReactiveRefreshTokenTokenResponseClient,它在授权服务器的令牌端点刷新访问令牌时使用 WebClient

WebClientReactiveRefreshTokenTokenResponseClient 是相当灵活的,因为它允许你定制令牌请求的预处理和/或令牌响应的后处理。

自定义 Access Token 请求

如果你需要定制令牌请求的预处理,你可以为 WebClientReactiveRefreshTokenTokenResponseClient.setParametersConverter() 提供一个自定义的 Converter<OAuth2RefreshTokenGrantRequest, MultiValueMap<String, String>>。默认的实现是建立一个 MultiValueMap<String, String>,只包含标准 OAuth 2.0 Access Token 请求grant_type 参数,用于构建请求。刷新令牌授予所需的其他参数由 WebClientReactiveRefreshTokenTokenResponseClient 直接添加到请求 body 中。然而,提供一个自定义 Converter,将允许你扩展标准的令牌请求并添加自定义参数。

如果你喜欢只添加额外的参数,你可以改为向 WebClientReactiveRefreshTokenTokenResponseClient.addParametersConverter() 提供一个自定义的 Converter<OAuth2RefreshTokenGrantRequest, MultiValueMap<String, String>,构建一个聚合的 Converter
自定义 Converter 必须返回 OAuth 2.0 Access Token 请求的有效参数,并能被预定的OAuth 2.0提供商理解。

自定义 Access Token 响应

在另一端,如果你需要定制令牌响应的后期处理,你需要为 WebClientReactiveRefreshTokenTokenResponseClient.setBodyExtractor() 提供一个自定义配置的 BodyExtractor<Mono<OAuth2AccessTokenResponse>, ReactiveHttpInputMessage>,用于将OAuth2.0 Access Token 响应转换为 OAuth2AccessTokenResponseOAuth2BodyExtractors.oauth2AccessTokenResponse() 提供的默认实现会解析响应并相应地处理错误。

自定义 WebClient

另外,如果你的要求更高级,你可以通过简单地提供 WebClientReactiveRefreshTokenTokenResponseClient.setWebClient() 与一个自定义配置的 WebClient 来完全控制请求/响应。

无论你是定制 WebClientReactiveRefreshTokenTokenResponseClient 还是提供你自己的 ReactiveOAuth2AccessTokenResponseClient 的实现,你都需要按照下面的例子来配置它。

Access Token Response Configuration
  • Java

  • Kotlin

// Customize
ReactiveOAuth2AccessTokenResponseClient<OAuth2RefreshTokenGrantRequest> refreshTokenTokenResponseClient = ...

ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider =
		ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
				.authorizationCode()
				.refreshToken(configurer -> configurer.accessTokenResponseClient(refreshTokenTokenResponseClient))
				.build();

...

authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
// Customize
val refreshTokenTokenResponseClient: ReactiveOAuth2AccessTokenResponseClient<OAuth2RefreshTokenGrantRequest> = ...

val authorizedClientProvider: ReactiveOAuth2AuthorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
        .authorizationCode()
        .refreshToken { it.accessTokenResponseClient(refreshTokenTokenResponseClient) }
        .build()

...

authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
ReactiveOAuth2AuthorizedClientProviderBuilder.builder().refreshToken() 配置了一个 RefreshTokenReactiveOAuth2AuthorizedClientProvider,这是 ReactiveOAuth2AuthorizedClientProvider 的一个实现,用于刷新令牌的授予(grant)。

OAuth2RefreshToken 可以选择性地在 authorization_codepassword 授予类型的访问令牌响应中返回。如果 OAuth2AuthorizedClient.getRefreshToken() 可用,而 OAuth2AuthorizedClient.getAccessToken() 已过期,它将自动由 RefreshTokenReactiveOAuth2AuthorizedClientProvider 刷新。

客户端凭证

请参考OAuth 2.0授权框架,了解关于 客户凭证 授予的进一步细节。

请求 Access Token

请参考客户端凭证授予的 Access Token 请求/响应 协议流程。

客户端凭证授予的 ReactiveOAuth2AccessTokenResponseClient 的默认实现是 WebClientReactiveClientCredentialsTokenResponseClient,它在授权服务器的令牌端点请求访问令牌时使用 WebClient

WebClientReactiveClientCredentialsTokenResponseClient 是相当灵活的,因为它允许你定制令牌请求的预处理和/或令牌响应的后处理。

自定义 Access Token 请求

如果你需要定制令牌请求的预处理,你可以为 WebClientReactiveClientCredentialsTokenResponseClient.setParametersConverter() 提供一个自定义的 Converter<OAuth2ClientCredentialsGrantRequest, MultiValueMap<String, String>>。默认的实现是建立一个 MultiValueMap<String, String>,只包含标准 OAuth 2.0 Access Token 请求grant_type 参数,用于构建请求。客户端凭证授予所需的其他参数由 WebClientReactiveClientCredentialsTokenResponseClient 直接添加到请求 body 中。然而,提供一个自定义的 Converter,将允许你扩展标准的令牌请求并添加自定义参数。

如果你喜欢只添加额外的参数,你可以向 WebClientReactiveClientCredentialsTokenResponseClient.addParametersConverter() 提供一个自定义的 Converter<OAuth2ClientCredentialsGrantRequest, MultiValueMap<String, String>>,构建一个聚合的 Converter
自定义 Converter 必须返回 OAuth 2.0 Access Token 请求的有效参数,并能被预定的OAuth 2.0提供商理解。

自定义 Access Token 响应

在另一端,如果你需要定制令牌响应的后期处理,你需要为 WebClientReactiveClientCredentialsTokenResponseClient.setBodyExtractor() 提供一个自定义配置的 BodyExtractor<Mono<OAuth2AccessTokenResponse>, ReactiveHttpInputMessage>,用于将OAuth2.0访问令牌响应转换为 OAuth2AccessTokenResponseOAuth2BodyExtractors.oauth2AccessTokenResponse() 提供的默认实现会解析响应并相应地处理错误。

自定义 WebClient

另外,如果你的要求更高级,你可以通过简单地提供 WebClientReactiveClientCredentialsTokenResponseClient.setWebClient() 与一个自定义配置的 WebClient 来完全控制请求/响应。

无论你是定制 WebClientReactiveClientCredentialsTokenResponseClient 还是提供你自己的 ReactiveOAuth2AccessTokenResponseClient 的实现,你都需要按照下面的例子来配置它。

  • Java

  • Kotlin

// Customize
ReactiveOAuth2AccessTokenResponseClient<OAuth2ClientCredentialsGrantRequest> clientCredentialsTokenResponseClient = ...

ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider =
		ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
				.clientCredentials(configurer -> configurer.accessTokenResponseClient(clientCredentialsTokenResponseClient))
				.build();

...

authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
// Customize
val clientCredentialsTokenResponseClient: ReactiveOAuth2AccessTokenResponseClient<OAuth2ClientCredentialsGrantRequest> = ...

val authorizedClientProvider: ReactiveOAuth2AuthorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
        .clientCredentials { it.accessTokenResponseClient(clientCredentialsTokenResponseClient) }
        .build()

...

authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
ReactiveOAuth2AuthorizedClientProviderBuilder.builder().clientCredentials() 配置了一个 ClientCredentialsReactiveOAuth2AuthorizedClientProvider,它是 ReactiveOAuth2AuthorizedClientProvider 的一个实现,用于客户端凭证授予。

使用 Access Token

给出以下Spring Boot 2.x属性,用于OAuth 2.0客户端注册。

spring:
  security:
    oauth2:
      client:
        registration:
          okta:
            client-id: okta-client-id
            client-secret: okta-client-secret
            authorization-grant-type: client_credentials
            scope: read, write
        provider:
          okta:
            token-uri: https://dev-1234.oktapreview.com/oauth2/v1/token

…​和 ReactiveOAuth2AuthorizedClientManager @Bean

  • Java

  • Kotlin

@Bean
public ReactiveOAuth2AuthorizedClientManager authorizedClientManager(
		ReactiveClientRegistrationRepository clientRegistrationRepository,
		ServerOAuth2AuthorizedClientRepository authorizedClientRepository) {

	ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider =
			ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
					.clientCredentials()
					.build();

	DefaultReactiveOAuth2AuthorizedClientManager authorizedClientManager =
			new DefaultReactiveOAuth2AuthorizedClientManager(
					clientRegistrationRepository, authorizedClientRepository);
	authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);

	return authorizedClientManager;
}
@Bean
fun authorizedClientManager(
        clientRegistrationRepository: ReactiveClientRegistrationRepository,
        authorizedClientRepository: ServerOAuth2AuthorizedClientRepository): ReactiveOAuth2AuthorizedClientManager {
    val authorizedClientProvider: ReactiveOAuth2AuthorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
            .clientCredentials()
            .build()
    val authorizedClientManager = DefaultReactiveOAuth2AuthorizedClientManager(
            clientRegistrationRepository, authorizedClientRepository)
    authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
    return authorizedClientManager
}

你可以通过以下方式获得 OAuth2AccessToken

  • Java

  • Kotlin

@Controller
public class OAuth2ClientController {

	@Autowired
	private ReactiveOAuth2AuthorizedClientManager authorizedClientManager;

	@GetMapping("/")
	public Mono<String> index(Authentication authentication, ServerWebExchange exchange) {
		OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
				.principal(authentication)
				.attribute(ServerWebExchange.class.getName(), exchange)
				.build();

		return this.authorizedClientManager.authorize(authorizeRequest)
				.map(OAuth2AuthorizedClient::getAccessToken)
				...
				.thenReturn("index");
	}
}
class OAuth2ClientController {

    @Autowired
    private lateinit var authorizedClientManager: ReactiveOAuth2AuthorizedClientManager

    @GetMapping("/")
    fun index(authentication: Authentication, exchange: ServerWebExchange): Mono<String> {
        val authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
                .principal(authentication)
                .attribute(ServerWebExchange::class.java.name, exchange)
                .build()

        return authorizedClientManager.authorize(authorizeRequest)
                .map { it.accessToken }
                ...
                .thenReturn("index")
    }
}
ServerWebExchange 是一个 OPTIONAL (可选的)属性。如果没有提供,它将通过 ServerWebExchange.class key 从 Reactor 的 Context 中获得。

资源所有者的密码凭证

请参考OAuth 2.0授权框架,了解关于 资源所有者密码凭证 授予的进一步细节。

请求 Access Token

请参考 Access Token 请求/响应 协议流程,了解资源所有者密码凭证授予。

资源所有者密码凭证授予的 ReactiveOAuth2AccessTokenResponseClient 的默认实现是 WebClientReactivePasswordTokenResponseClient,它在授权服务器的令牌端点请求访问令牌时使用 WebClient

WebClientReactivePasswordTokenResponseClient 是相当灵活的,因为它允许你定制令牌请求的预处理和/或令牌响应的后处理。

自定义 Access Token 请求

如果你需要定制令牌请求的预处理,你可以为 WebClientReactivePasswordTokenResponseClient.setParametersConverter() 提供一个自定义的 Converter<OAuth2PasswordGrantRequest, MultiValueMap<String, String>>。默认的实现是建立一个 MultiValueMap<String, String>,只包含标准 OAuth 2.0 Access Token Requestgrant_type 参数,用于构建请求。资源所有者密码凭证授予所需的其他参数由 WebClientReactivePasswordTokenResponseClient 直接添加到请求正文中。然而,提供一个自定义 Converter,将允许你扩展标准的令牌请求并添加自定义参数。

如果你喜欢只添加额外的参数,你可以向 WebClientReactivePasswordTokenResponseClient.addParametersConverter() 提供一个自定义的 Converter<OAuth2PasswordGrantRequest, MultiValueMap<String, String>>,构建一个聚合的 Converter
自定义 Converter 必须返回OAuth 2.0访问令牌请求的有效参数,并能被预期的OAuth 2.0提供商理解。

自定义 Access Token 响应

在另一端,如果你需要定制令牌响应的后处理,你需要为 WebClientReactivePasswordTokenResponseClient.setBodyExtractor() 提供一个自定义配置的 BodyExtractor<Mono<OAuth2AccessTokenResponse>, ReactiveHttpInputMessage>,用于将OAuth2.0访问令牌响应转换为 OAuth2AccessTokenResponseOAuth2BodyExtractors.oauth2AccessTokenResponse() 提供的默认实现会解析响应并相应地处理错误。

自定义 WebClient

另外,如果你的要求更高级,你可以通过简单地提供 WebClientReactivePasswordTokenResponseClient.setWebClient() 与一个自定义配置的 WebClient 来完全控制请求/响应。

无论你是定制 WebClientReactivePasswordTokenResponseClient 还是提供你自己的 ReactiveOAuth2AccessTokenResponseClient 的实现,你都需要按照下面的例子来配置它。

  • Java

  • Kotlin

// Customize
ReactiveOAuth2AccessTokenResponseClient<OAuth2PasswordGrantRequest> passwordTokenResponseClient = ...

ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider =
		ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
				.password(configurer -> configurer.accessTokenResponseClient(passwordTokenResponseClient))
				.refreshToken()
				.build();

...

authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
val passwordTokenResponseClient: ReactiveOAuth2AccessTokenResponseClient<OAuth2PasswordGrantRequest> = ...

val authorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
        .password { it.accessTokenResponseClient(passwordTokenResponseClient) }
        .refreshToken()
        .build()

...

authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
ReactiveOAuth2AuthorizedClientProviderBuilder.builder().password() 配置了一个 PasswordReactiveOAuth2AuthorizedClientProvider,它是 ReactiveOAuth2AuthorizedClientProvider 的实现,用于资源所有者密码凭证授予。

使用 Access Token

给出以下Spring Boot 2.x属性,用于OAuth 2.0客户端注册。

spring:
  security:
    oauth2:
      client:
        registration:
          okta:
            client-id: okta-client-id
            client-secret: okta-client-secret
            authorization-grant-type: password
            scope: read, write
        provider:
          okta:
            token-uri: https://dev-1234.oktapreview.com/oauth2/v1/token

…​和 ReactiveOAuth2AuthorizedClientManager @Bean:

  • Java

  • Kotlin

@Bean
public ReactiveOAuth2AuthorizedClientManager authorizedClientManager(
		ReactiveClientRegistrationRepository clientRegistrationRepository,
		ServerOAuth2AuthorizedClientRepository authorizedClientRepository) {

	ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider =
			ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
					.password()
					.refreshToken()
					.build();

	DefaultReactiveOAuth2AuthorizedClientManager authorizedClientManager =
			new DefaultReactiveOAuth2AuthorizedClientManager(
					clientRegistrationRepository, authorizedClientRepository);
	authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);

	// Assuming the `username` and `password` are supplied as `ServerHttpRequest` parameters,
	// map the `ServerHttpRequest` parameters to `OAuth2AuthorizationContext.getAttributes()`
	authorizedClientManager.setContextAttributesMapper(contextAttributesMapper());

	return authorizedClientManager;
}

private Function<OAuth2AuthorizeRequest, Mono<Map<String, Object>>> contextAttributesMapper() {
	return authorizeRequest -> {
		Map<String, Object> contextAttributes = Collections.emptyMap();
		ServerWebExchange exchange = authorizeRequest.getAttribute(ServerWebExchange.class.getName());
		ServerHttpRequest request = exchange.getRequest();
		String username = request.getQueryParams().getFirst(OAuth2ParameterNames.USERNAME);
		String password = request.getQueryParams().getFirst(OAuth2ParameterNames.PASSWORD);
		if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
			contextAttributes = new HashMap<>();

			// `PasswordReactiveOAuth2AuthorizedClientProvider` requires both attributes
			contextAttributes.put(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, username);
			contextAttributes.put(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, password);
		}
		return Mono.just(contextAttributes);
	};
}
@Bean
fun authorizedClientManager(
        clientRegistrationRepository: ReactiveClientRegistrationRepository,
        authorizedClientRepository: ServerOAuth2AuthorizedClientRepository): ReactiveOAuth2AuthorizedClientManager {
    val authorizedClientProvider: ReactiveOAuth2AuthorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
            .password()
            .refreshToken()
            .build()
    val authorizedClientManager = DefaultReactiveOAuth2AuthorizedClientManager(
            clientRegistrationRepository, authorizedClientRepository)
    authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)

    // Assuming the `username` and `password` are supplied as `ServerHttpRequest` parameters,
    // map the `ServerHttpRequest` parameters to `OAuth2AuthorizationContext.getAttributes()`
    authorizedClientManager.setContextAttributesMapper(contextAttributesMapper())
    return authorizedClientManager
}

private fun contextAttributesMapper(): Function<OAuth2AuthorizeRequest, Mono<MutableMap<String, Any>>> {
    return Function { authorizeRequest ->
        var contextAttributes: MutableMap<String, Any> = mutableMapOf()
        val exchange: ServerWebExchange = authorizeRequest.getAttribute(ServerWebExchange::class.java.name)!!
        val request: ServerHttpRequest = exchange.request
        val username: String? = request.queryParams.getFirst(OAuth2ParameterNames.USERNAME)
        val password: String? = request.queryParams.getFirst(OAuth2ParameterNames.PASSWORD)
        if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
            contextAttributes = hashMapOf()

            // `PasswordReactiveOAuth2AuthorizedClientProvider` requires both attributes
            contextAttributes[OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME] = username!!
            contextAttributes[OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME] = password!!
        }
        Mono.just(contextAttributes)
    }
}

你可以通过以下方式获得 OAuth2AccessToken

  • Java

  • Kotlin

@Controller
public class OAuth2ClientController {

	@Autowired
	private ReactiveOAuth2AuthorizedClientManager authorizedClientManager;

	@GetMapping("/")
	public Mono<String> index(Authentication authentication, ServerWebExchange exchange) {
		OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
				.principal(authentication)
				.attribute(ServerWebExchange.class.getName(), exchange)
				.build();

		return this.authorizedClientManager.authorize(authorizeRequest)
				.map(OAuth2AuthorizedClient::getAccessToken)
				...
				.thenReturn("index");
	}
}
@Controller
class OAuth2ClientController {
    @Autowired
    private lateinit var authorizedClientManager: ReactiveOAuth2AuthorizedClientManager

    @GetMapping("/")
    fun index(authentication: Authentication, exchange: ServerWebExchange): Mono<String> {
        val authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
                .principal(authentication)
                .attribute(ServerWebExchange::class.java.name, exchange)
                .build()

        return authorizedClientManager.authorize(authorizeRequest)
                .map { it.accessToken }
                ...
                .thenReturn("index")
    }
}
ServerWebExchange 是一个 OPTIONAL 属性。如果没有提供,它将通过 ServerWebExchange.class key 从 Reactor 的 Context 中获得。

JWT Bearer

关于 JWT Bearer 授予的进一步细节,请参考OAuth 2.0客户端认证和授权授予的JSON Web Token(JWT)配置文件。

请求 Access Token

请参考 Access Token 请求/响应 协议流程,了解 JWT Bearer 的授予。

JWT Bearer 授予的 ReactiveOAuth2AccessTokenResponseClient 的默认实现是 WebClientReactiveJwtBearerTokenResponseClient,它在授权服务器的令牌端点请求访问令牌时使用 WebClient

WebClientReactiveJwtBearerTokenResponseClient 是相当灵活的,因为它允许你定制令牌请求的预处理和/或令牌响应的后处理。

自定义 Access Token 请求

如果你需要定制令牌请求的预处理,你可以为 WebClientReactiveJwtBearerTokenResponseClient.setParametersConverter() 提供一个自定义的 Converter<JwtBearerGrantRequest, MultiValueMap<String, String>>。默认的实现建立了一个 MultiValueMap<String, String>,只包含标准 OAuth 2.0 Access Token Requestgrant_type 参数,用于构建请求。JWT Bearer 授予所需的其他参数由 WebClientReactiveJwtBearerTokenResponseClient 直接添加到请求body中。然而,提供一个自定义的 Converter,将允许你扩展标准的令牌请求并添加自定义参数。

如果你喜欢只添加额外的参数,你可以改为向 WebClientReactiveJwtBearerTokenResponseClient.addParametersConverter() 提供一个自定义的 Converter<JwtBearerGrantRequest, MultiValueMap<String, String>,构建一个聚合 Converter
自定义 Converter 必须返回OAuth 2.0访问令牌请求的有效参数,并能被预定的OAuth 2.0提供商理解。

自定义 Access Token 响应

在另一端,如果你需要自定义令牌响应的后期处理,你需要为 WebClientReactiveJwtBearerTokenResponseClient.setBodyExtractor() 提供一个自定义配置的 BodyExtractor<Mono<OAuth2AccessTokenResponse>, ReactiveHttpInputMessage>,用于将OAuth2.0访问令牌响应转换为 OAuth2AccessTokenResponseOAuth2BodyExtractors.oauth2AccessTokenResponse() 提供的默认实现会解析响应并相应地处理错误。

自定义 WebClient

另外,如果你的要求更高级,你可以通过简单地提供 WebClientReactiveJwtBearerTokenResponseClient.setWebClient() 与一个自定义配置的 WebClient 来完全控制请求/响应。

无论你是定制 WebClientReactiveJwtBearerTokenResponseClient 还是提供你自己的 ReactiveOAuth2AccessTokenResponseClient 的实现,你都需要按照下面的例子来配置它。

  • Java

  • Kotlin

// Customize
ReactiveOAuth2AccessTokenResponseClient<JwtBearerGrantRequest> jwtBearerTokenResponseClient = ...

JwtBearerReactiveOAuth2AuthorizedClientProvider jwtBearerAuthorizedClientProvider = new JwtBearerReactiveOAuth2AuthorizedClientProvider();
jwtBearerAuthorizedClientProvider.setAccessTokenResponseClient(jwtBearerTokenResponseClient);

ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider =
		ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
				.provider(jwtBearerAuthorizedClientProvider)
				.build();

...

authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
// Customize
val jwtBearerTokenResponseClient: ReactiveOAuth2AccessTokenResponseClient<JwtBearerGrantRequest> = ...

val jwtBearerAuthorizedClientProvider = JwtBearerReactiveOAuth2AuthorizedClientProvider()
jwtBearerAuthorizedClientProvider.setAccessTokenResponseClient(jwtBearerTokenResponseClient)

val authorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
        .provider(jwtBearerAuthorizedClientProvider)
        .build()

...

authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)

使用 Access Token

给出以下Spring Boot 2.x属性,用于OAuth 2.0客户端注册。

spring:
  security:
    oauth2:
      client:
        registration:
          okta:
            client-id: okta-client-id
            client-secret: okta-client-secret
            authorization-grant-type: urn:ietf:params:oauth:grant-type:jwt-bearer
            scope: read
        provider:
          okta:
            token-uri: https://dev-1234.oktapreview.com/oauth2/v1/token

…​and the OAuth2AuthorizedClientManager @Bean:

  • Java

  • Kotlin

@Bean
public ReactiveOAuth2AuthorizedClientManager authorizedClientManager(
		ReactiveClientRegistrationRepository clientRegistrationRepository,
		ServerOAuth2AuthorizedClientRepository authorizedClientRepository) {

	JwtBearerReactiveOAuth2AuthorizedClientProvider jwtBearerAuthorizedClientProvider =
			new JwtBearerReactiveOAuth2AuthorizedClientProvider();

	ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider =
			ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
					.provider(jwtBearerAuthorizedClientProvider)
					.build();

	DefaultReactiveOAuth2AuthorizedClientManager authorizedClientManager =
			new DefaultReactiveOAuth2AuthorizedClientManager(
					clientRegistrationRepository, authorizedClientRepository);
	authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);

	return authorizedClientManager;
}
@Bean
fun authorizedClientManager(
        clientRegistrationRepository: ReactiveClientRegistrationRepository,
        authorizedClientRepository: ServerOAuth2AuthorizedClientRepository): ReactiveOAuth2AuthorizedClientManager {
    val jwtBearerAuthorizedClientProvider = JwtBearerReactiveOAuth2AuthorizedClientProvider()
    val authorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
            .provider(jwtBearerAuthorizedClientProvider)
            .build()
    val authorizedClientManager = DefaultReactiveOAuth2AuthorizedClientManager(
            clientRegistrationRepository, authorizedClientRepository)
    authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
    return authorizedClientManager
}

You may obtain the OAuth2AccessToken as follows:

  • Java

  • Kotlin

@RestController
public class OAuth2ResourceServerController {

	@Autowired
	private ReactiveOAuth2AuthorizedClientManager authorizedClientManager;

	@GetMapping("/resource")
	public Mono<String> resource(JwtAuthenticationToken jwtAuthentication, ServerWebExchange exchange) {
		OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
				.principal(jwtAuthentication)
				.build();

		return this.authorizedClientManager.authorize(authorizeRequest)
				.map(OAuth2AuthorizedClient::getAccessToken)
				...
	}
}
class OAuth2ResourceServerController {

    @Autowired
    private lateinit var authorizedClientManager: ReactiveOAuth2AuthorizedClientManager

    @GetMapping("/resource")
    fun resource(jwtAuthentication: JwtAuthenticationToken, exchange: ServerWebExchange): Mono<String> {
        val authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
                .principal(jwtAuthentication)
                .build()
        return authorizedClientManager.authorize(authorizeRequest)
                .map { it.accessToken }
                ...
    }
}
JwtBearerReactiveOAuth2AuthorizedClientProvider 默认通过 OAuth2AuthorizationContext.getPrincipal().getPrincipal() 解析Jwt断言(assertion),因此在前面的例子中使用了 JwtAuthenticationToken
如果你需要从不同的来源解析 Jwt 断言(assertion),你可以为 JwtBearerReactiveOAuth2AuthorizedClientProvider.setJwtAssertionResolver() 提供一个自定义 Function<OAuth2AuthorizationContext, Mono<Jwt>>