# 授权赠款支助

# 授权代码

有关授权代码 (opens new window)授权的更多详细信息,请参阅 OAuth2.0 授权框架。

# 获得授权

请参阅授权请求/回应 (opens new window)协议流以获得授权代码授权。

# 发起授权请求

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

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

给出了 OAuth2.0 客户端注册的以下 Spring Boot2.x 属性:

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重定向的授权请求,并最终启动授权代码授予流。

AuthorizationCodeReactiveOAuth2AuthorizedClientProvider是用于授权代码授予的ReactiveOAuth2AuthorizedClientProvider的实现,
还通过OAuth2AuthorizationRequestRedirectWebFilter发起重定向的授权请求。

如果 OAuth2.0 客户端是公共客户 (opens new window),则按照以下方式配置 OAuth2.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"
            ...

使用代码交换的证明密钥 (opens new window)支持公共客户端。如果客户机运行在不受信任的环境中(例如,本地应用程序或基于 Web 浏览器的应用程序),因此不能维护其凭据的机密性,则当以下条件成立时,将自动使用 PKCE:

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

  2. client-authentication-method设置为“无”(ClientAuthenticationMethod.NONE

DefaultServerOAuth2AuthorizationRequestResolver还支持URI使用UriComponentsBuilderredirect-uri模板变量。

以下配置使用了所有受支持的URI模板变量:

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

当 OAuth2.0 客户端运行在代理服务器之后时,使用redirect-uri模板变量配置URI模板变量特别有用。这确保了在展开redirect-uri时使用X-Forwarded-*头。

# 自定义授权请求

ServerOAuth2AuthorizationRequestResolver可以实现的主要用例之一是,能够使用 OAuth2.0 授权框架中定义的标准参数之上的附加参数来定制授权请求。

例如,OpenID Connect 为授权代码流 (opens new window)定义了额外的 OAuth2.0 请求参数,它是从OAuth2.0 授权框架 (opens new window)中定义的标准参数扩展而来的。其中一个扩展参数是prompt参数。

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

下面的示例展示了如何使用DefaultServerOAuth2AuthorizationRequestResolver配置Consumer<OAuth2AuthorizationRequest.Builder>,该配置通过包括请求参数oauth2Login()来定制oauth2Login()的授权请求。

爪哇

@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"));
	}
}

Kotlin

@EnableWebFluxSecurity
class SecurityConfig {

    @Autowired
    private lateinit var customClientRegistrationRepository: ReactiveClientRegistrationRepository

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

    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属性。

爪哇

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

Kotlin

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的自定义实现,则可以按照以下示例对其进行配置:

例 1。ServerAuthorizationRequestRepository 配置

爪哇

@EnableWebFluxSecurity
public class OAuth2ClientSecurityConfig {

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

Kotlin

@EnableWebFluxSecurity
class OAuth2ClientSecurityConfig {

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

# 请求访问令牌

请参阅访问令牌请求/响应 (opens new window)协议流以获得授权代码授权。

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

WebClientReactiveAuthorizationCodeTokenResponseClient非常灵活,因为它允许你定制令牌请求的预处理和/或令牌响应的后处理。

# 自定义访问令牌请求

如果需要定制令牌请求的预处理,则可以提供带有自定义WebClientReactiveAuthorizationCodeTokenResponseClient.setParametersConverter()Converter<OAuth2AuthorizationCodeGrantRequest, MultiValueMap<String, String>>。默认实现构建一个MultiValueMap<String, String>,该实现仅包含用于构造请求的标准OAuth2.0 访问令牌请求 (opens new window)grant_type参数。授权代码授权所需的其他参数由WebClientReactiveAuthorizationCodeTokenResponseClient直接添加到请求主体中。但是,提供一个自定义Converter,将允许你扩展标准令牌请求并添加自定义参数。

如果你只喜欢添加额外的参数,那么可以使用自定义的Converter<OAuth2AuthorizationCodeGrantRequest, MultiValueMap<String, String>>WebClientReactiveAuthorizationCodeTokenResponseClient.addParametersConverter()提供Converter<OAuth2AuthorizationCodeGrantRequest, MultiValueMap<String, String>>,它构造一个聚合Converter
自定义Converter必须返回 OAuth2.0 访问令牌请求的有效参数,该请求被预期的 OAuth2.0 提供程序理解。

# 自定义访问令牌响应

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

# 自定义WebClient

或者,如果你的需求更高级,那么你可以通过简单地提供WebClientReactiveAuthorizationCodeTokenResponseClient.setWebClient()和自定义配置的WebClient来完全控制请求/响应。

无论你是自定义WebClientReactiveAuthorizationCodeTokenResponseClient还是提供你自己的ReactiveOAuth2AccessTokenResponseClient实现,你都需要对其进行配置,如以下示例所示:

例 2。访问令牌响应配置

爪哇

@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);
	}
}

Kotlin

@EnableWebFluxSecurity
class OAuth2ClientSecurityConfig {

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

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

        return OAuth2AuthorizationCodeReactiveAuthenticationManager(accessTokenResponseClient)
    }
}

# 刷新令牌

有关刷新令牌 (opens new window)的更多详细信息,请参阅 OAuth2.0 授权框架。

# 刷新访问令牌

请参阅访问令牌请求/响应 (opens new window)协议流以获取刷新令牌授权。

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

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

# 自定义访问令牌请求

如果需要定制令牌请求的预处理,则可以提供带有自定义WebClientReactiveRefreshTokenTokenResponseClient.setParametersConverter()Converter<OAuth2RefreshTokenGrantRequest, MultiValueMap<String, String>>。默认实现构建一个MultiValueMap<String, String>,其中只包含用于构造请求的标准OAuth2.0 访问令牌请求 (opens new window)grant_type参数。刷新令牌授权所需的其他参数由WebClientReactiveRefreshTokenTokenResponseClient直接添加到请求主体中。但是,提供一个自定义Converter,将允许你扩展标准令牌请求并添加自定义参数。

如果你只喜欢添加额外的参数,那么你可以使用自定义的WebClientReactiveRefreshTokenTokenResponseClient.addParametersConverter()提供Converter<OAuth2RefreshTokenGrantRequest, MultiValueMap<String, String>>,它构造一个聚合Converter
自定义Converter必须返回 OAuth2.0 访问令牌请求的有效参数,该请求被预期的 OAuth2.0 提供程序理解。

# 自定义访问令牌响应

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

# 自定义WebClient

或者,如果你的需求更高级,那么你可以通过简单地提供WebClientReactiveRefreshTokenTokenResponseClient.setWebClient()和自定义配置的WebClient来完全控制请求/响应。

无论你是自定义WebClientReactiveRefreshTokenTokenResponseClient还是提供你自己的ReactiveOAuth2AccessTokenResponseClient实现,你都需要对其进行配置,如以下示例所示:

例 3。访问令牌响应配置

爪哇

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

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

...

authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);

Kotlin

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

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

...

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

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

# 客户凭据

有关客户凭据 (opens new window)授权的更多详细信息,请参阅 OAuth2.0 授权框架。

# 请求访问令牌

请参阅访问令牌请求/响应 (opens new window)协议流以获取客户端凭据授权。

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

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

# 自定义访问令牌请求

如果需要定制令牌请求的预处理,则可以提供带有自定义WebClientReactiveClientCredentialsTokenResponseClient.setParametersConverter()Converter<OAuth2ClientCredentialsGrantRequest, MultiValueMap<String, String>>。默认实现构建一个MultiValueMap<String, String>,该实现仅包含用于构造请求的标准OAuth2.0 访问令牌请求 (opens new window)grant_type参数。由WebClientReactiveClientCredentialsTokenResponseClient直接将客户机凭据授权所需的其他参数添加到请求主体中。但是,提供一个自定义Converter,将允许你扩展标准令牌请求并添加自定义参数。

如果你只喜欢添加额外的参数,那么可以使用自定义的Converter<OAuth2ClientCredentialsGrantRequest, MultiValueMap<String, String>>WebClientReactiveClientCredentialsTokenResponseClient.addParametersConverter()提供Converter<OAuth2ClientCredentialsGrantRequest, MultiValueMap<String, String>>,它构造一个聚合Converter
自定义Converter必须返回 OAuth2.0 访问令牌请求的有效参数,该请求被预期的 OAuth2.0 提供程序理解。

# 自定义访问令牌响应

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

# 自定义WebClient

或者,如果你的需求更高级,你可以通过简单地提供WebClientReactiveClientCredentialsTokenResponseClient.setWebClient()和自定义配置的WebClient来完全控制请求/响应。

无论你是自定义WebClientReactiveClientCredentialsTokenResponseClient还是提供你自己的ReactiveOAuth2AccessTokenResponseClient实现,你都需要对其进行配置,如以下示例所示:

爪哇

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

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

...

authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);

Kotlin

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

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

...

authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
ReactiveOAuth2AuthorizedClientProviderBuilder.builder().clientCredentials()配置ClientCredentialsReactiveOAuth2AuthorizedClientProvider
,这是用于客户端凭据授权的ReactiveOAuth2AuthorizedClientProvider的实现。

# 使用访问令牌

给出了用于 OAuth2.0 客户端注册的以下 Boot2.x 属性:

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:

爪哇

@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;
}

Kotlin

@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:

爪哇

@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");
	}
}

Kotlin

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是一个可选属性。
如果不提供,它将通过反应堆的背景 (opens new window)键从ServerWebExchange.class获得。

# 资源所有者密码凭据

有关资源所有者密码凭据 (opens new window)授权的更多详细信息,请参阅 OAuth2.0 授权框架。

# 请求访问令牌

请参阅访问令牌请求/响应 (opens new window)协议流以获取资源所有者密码凭据授权。

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

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

# 自定义访问令牌请求

如果需要对令牌请求的预处理进行自定义,则可以提供带有自定义WebClientReactivePasswordTokenResponseClient.setParametersConverter()Converter<OAuth2PasswordGrantRequest, MultiValueMap<String, String>>。默认的实现构建一个MultiValueMap<String, String>,其中只包含用于构造请求的标准OAuth2.0 访问令牌请求 (opens new window)grant_type参数。通过WebClientReactivePasswordTokenResponseClient将资源所有者密码凭据授予所需的其他参数直接添加到请求的主体中。但是,提供一个自定义Converter,将允许你扩展标准令牌请求并添加自定义参数。

如果你只喜欢添加额外的参数,那么你可以使用自定义的WebClientReactivePasswordTokenResponseClient.addParametersConverter()提供Converter<OAuth2PasswordGrantRequest, MultiValueMap<String, String>>,它构造一个聚合Converter
自定义Converter必须返回 OAuth2.0 访问令牌请求的有效参数,该请求被预期的 OAuth2.0 提供程序理解。

# 自定义访问令牌响应

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

# 自定义WebClient

或者,如果你的需求更高级,你可以通过简单地提供WebClientReactivePasswordTokenResponseClient.setWebClient()和自定义配置的WebClient来完全控制请求/响应。

无论你是自定义WebClientReactivePasswordTokenResponseClient还是提供你自己的ReactiveOAuth2AccessTokenResponseClient实现,你都需要对其进行配置,如以下示例所示:

爪哇

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

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

...

authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);

Kotlin

val passwordTokenResponseClient: ReactiveOAuth2AccessTokenResponseClient<OAuth2PasswordGrantRequest> = ...

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

...

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

# 使用访问令牌

给出了用于 OAuth2.0 客户端注册的以下 Boot2.x 属性:

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:

爪哇

@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);
	};
}

Kotlin

@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:

爪哇

@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");
	}
}

Kotlin

@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是一个可选属性。
如果不提供,它将通过反应堆的背景 (opens new window)键从ServerWebExchange.class获得。

# JWT 持有人

有关JWT Bearer (opens new window)授权的更多详细信息,请参考 JSON Web Token 配置文件的 OAuth2.0 客户端身份验证和授权授权。

# 请求访问令牌

请参阅访问令牌请求/响应 (opens new window)协议流以获取 JWT 承载授权。

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

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

# 自定义访问令牌请求

如果需要对令牌请求的预处理进行自定义,则可以提供带有自定义WebClientReactiveJwtBearerTokenResponseClient.setParametersConverter()Converter<JwtBearerGrantRequest, MultiValueMap<String, String>>。默认的实现构建一个MultiValueMap<String, String>,其中只包含用于构造请求的标准OAuth2.0 访问令牌请求 (opens new window)grant_type参数。JWT 承载授权所需的其他参数由WebClientReactiveJwtBearerTokenResponseClient直接添加到请求的主体中。但是,提供一个自定义Converter,将允许你扩展标准令牌请求并添加自定义参数。

如果你只喜欢添加额外的参数,那么可以使用自定义的Converter<JwtBearerGrantRequest, MultiValueMap<String, String>>WebClientReactiveJwtBearerTokenResponseClient.addParametersConverter()提供Converter<JwtBearerGrantRequest, MultiValueMap<String, String>>,它构造一个聚合Converter
自定义Converter必须返回 OAuth2.0 访问令牌请求的有效参数,该请求被预期的 OAuth2.0 提供程序理解。

# 自定义访问令牌响应

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

# 自定义WebClient

或者,如果你的需求更高级,你可以通过简单地提供WebClientReactiveJwtBearerTokenResponseClient.setWebClient()和自定义配置的WebClient来完全控制请求/响应。

无论你是自定义WebClientReactiveJwtBearerTokenResponseClient还是提供你自己的ReactiveOAuth2AccessTokenResponseClient实现,你都需要对其进行配置,如以下示例所示:

爪哇

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

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

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

...

authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);

Kotlin

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

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

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

...

authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)

# 使用访问令牌

给出了用于 OAuth2.0 客户端注册的以下 Spring Boot2.x 属性:

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

…和OAuth2AuthorizedClientManager``@Bean:

爪哇

@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;
}

Kotlin

@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
}

你可以按以下方式获得OAuth2AccessToken:

爪哇

@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)
				...
	}
}

Kotlin

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 }
                ...
    }
}

核心接口和类OAuth2 客户端身份验证