|
此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Security 6.4.3! |
授权授予支持
授权码
| 请参阅 OAuth 2.0 授权框架,了解有关授权码授予的更多详细信息。 |
获取授权
| 请参阅授权请求/响应协议流程,了解授权码授予。 |
发起授权请求
这OAuth2AuthorizationRequestRedirectFilter使用OAuth2AuthorizationRequestResolver要解析OAuth2AuthorizationRequest并通过将最终用户的用户代理重定向到授权服务器的授权端点来启动授权代码授予流程。
主要角色OAuth2AuthorizationRequestResolver是解析OAuth2AuthorizationRequest从提供的 Web 请求。
默认实现DefaultOAuth2AuthorizationRequestResolver(默认)路径上的 matches/oauth2/authorization/{registrationId}提取registrationId并使用它来构建OAuth2AuthorizationRequest对于关联的ClientRegistration.
给定 OAuth 2.0 客户端注册的以下 Spring Boot 2.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将启动 Authorization Request 重定向OAuth2AuthorizationRequestRedirectFilter并最终启动授权代码授予流程。
这AuthorizationCodeOAuth2AuthorizedClientProvider是OAuth2AuthorizedClientProvider对于 Authorization Code 授予,
它还通过OAuth2AuthorizationRequestRedirectFilter. |
如果 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:
-
client-secret被省略(或为空) -
client-authentication-method设置为 “none” (ClientAuthenticationMethod.NONE)
如果 OAuth 2.0 提供者支持机密客户端的 PKCE,您可以(可选)使用DefaultOAuth2AuthorizationRequestResolver.setAuthorizationRequestCustomizer(OAuth2AuthorizationRequestCustomizers.withPkce()). |
这DefaultOAuth2AuthorizationRequestResolver还支持URItemplate 变量的redirect-uri用UriComponentsBuilder.
以下配置使用所有支持的URI模板变量:
spring:
security:
oauth2:
client:
registration:
okta:
...
redirect-uri: "{baseScheme}://{baseHost}{basePort}{basePath}/authorized/{registrationId}"
...
{baseUrl}resolve为{baseScheme}://{baseHost}{basePort}{basePath}
|
配置redirect-uri跟URI当 OAuth 2.0 客户端在 Proxy Server 后面运行时,模板变量特别有用。
这可确保X-Forwarded-*扩展redirect-uri.
自定义授权请求
主要用例之一OAuth2AuthorizationRequestResolver可以实现的是能够使用高于 OAuth 2.0 授权框架中定义的标准参数的其他参数自定义授权请求。
例如,OpenID Connect 为授权代码流定义了其他 OAuth 2.0 请求参数,该请求参数从 OAuth 2.0 授权框架中定义的标准参数扩展而来。
其中一个扩展参数是prompt参数。
| 自选。以空格分隔、区分大小写的 ASCII 字符串值列表,用于指定 Authorization Server 是否提示最终用户重新进行身份验证和同意。定义的值为 none、login、consent select_account |
以下示例显示如何配置DefaultOAuth2AuthorizationRequestResolver替换为Consumer<OAuth2AuthorizationRequest.Builder>自定义oauth2Login(),通过包含 request 参数prompt=consent.
-
Java
-
Kotlin
@EnableWebSecurity
public class OAuth2LoginSecurityConfig {
@Autowired
private ClientRegistrationRepository clientRegistrationRepository;
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(authorize -> authorize
.anyRequest().authenticated()
)
.oauth2Login(oauth2 -> oauth2
.authorizationEndpoint(authorization -> authorization
.authorizationRequestResolver(
authorizationRequestResolver(this.clientRegistrationRepository)
)
)
);
return http.build();
}
private OAuth2AuthorizationRequestResolver authorizationRequestResolver(
ClientRegistrationRepository clientRegistrationRepository) {
DefaultOAuth2AuthorizationRequestResolver authorizationRequestResolver =
new DefaultOAuth2AuthorizationRequestResolver(
clientRegistrationRepository, "/oauth2/authorization");
authorizationRequestResolver.setAuthorizationRequestCustomizer(
authorizationRequestCustomizer());
return authorizationRequestResolver;
}
private Consumer<OAuth2AuthorizationRequest.Builder> authorizationRequestCustomizer() {
return customizer -> customizer
.additionalParameters(params -> params.put("prompt", "consent"));
}
}
@EnableWebSecurity
class SecurityConfig {
@Autowired
private lateinit var customClientRegistrationRepository: ClientRegistrationRepository
@Bean
open fun filterChain(http: HttpSecurity): SecurityFilterChain {
http {
authorizeRequests {
authorize(anyRequest, authenticated)
}
oauth2Login {
authorizationEndpoint {
authorizationRequestResolver = authorizationRequestResolver(customClientRegistrationRepository)
}
}
}
return http.build()
}
private fun authorizationRequestResolver(
clientRegistrationRepository: ClientRegistrationRepository?): OAuth2AuthorizationRequestResolver? {
val authorizationRequestResolver = DefaultOAuth2AuthorizationRequestResolver(
clientRegistrationRepository, "/oauth2/authorization")
authorizationRequestResolver.setAuthorizationRequestCustomizer(
authorizationRequestCustomizer())
return authorizationRequestResolver
}
private fun authorizationRequestCustomizer(): Consumer<OAuth2AuthorizationRequest.Builder> {
return Consumer { customizer ->
customizer
.additionalParameters { params -> params["prompt"] = "consent" }
}
}
}
对于简单的用例,其中特定提供商的附加请求参数始终相同,可以直接将其添加到authorization-uri财产。
例如,如果 request 参数prompt总是consent对于提供商okta,而不是简单地配置如下:
spring:
security:
oauth2:
client:
provider:
okta:
authorization-uri: https://dev-1234.oktapreview.com/oauth2/v1/authorize?prompt=consent
前面的示例显示了在标准参数之上添加自定义参数的常见使用案例。
或者,如果您的要求更高级,则只需覆盖OAuth2AuthorizationRequest.authorizationRequestUri财产。
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()
}
}
}
存储授权请求
这AuthorizationRequestRepository负责OAuth2AuthorizationRequest从发起授权请求到收到授权响应(回调)的时间。
这OAuth2AuthorizationRequest用于关联和验证授权响应。 |
的默认实现AuthorizationRequestRepository是HttpSessionOAuth2AuthorizationRequestRepository,它将OAuth2AuthorizationRequest在HttpSession.
如果您有AuthorizationRequestRepository,您可以按照以下示例所示对其进行配置:
-
Java
-
Kotlin
-
Xml
@EnableWebSecurity
public class OAuth2ClientSecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.oauth2Client(oauth2 -> oauth2
.authorizationCodeGrant(codeGrant -> codeGrant
.authorizationRequestRepository(this.authorizationRequestRepository())
...
)
.oauth2Login(oauth2 -> oauth2
.authorizationEndpoint(endpoint -> endpoint
.authorizationRequestRepository(this.authorizationRequestRepository())
...
)
).build();
}
@Bean
public AuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository() {
return new CustomOAuth2AuthorizationRequestRepository();
}
}
@EnableWebSecurity
class OAuth2ClientSecurityConfig {
@Bean
open fun filterChain(http: HttpSecurity): SecurityFilterChain {
http {
oauth2Client {
authorizationCodeGrant {
authorizationRequestRepository = authorizationRequestRepository()
}
}
}
return http.build()
}
}
<http>
<oauth2-client>
<authorization-code-grant authorization-request-repository-ref="authorizationRequestRepository"/>
</oauth2-client>
</http>
申请 Access Token
| 请参阅访问令牌请求/响应协议流程,了解授权码的授予。 |
的默认实现OAuth2AccessTokenResponseClient的授权码 grant 为DefaultAuthorizationCodeTokenResponseClient,它使用RestOperations用于在 Authorization Server 的令牌端点上将授权码交换为访问令牌。
这DefaultAuthorizationCodeTokenResponseClient非常灵活,因为它允许您自定义令牌请求的预处理和/或令牌响应的后处理。
自定义 Access Token 请求
如果需要自定义 Token Request 的预处理,可以提供DefaultAuthorizationCodeTokenResponseClient.setRequestEntityConverter()使用自定义Converter<OAuth2AuthorizationCodeGrantRequest, RequestEntity<?>>.
默认实现OAuth2AuthorizationCodeGrantRequestEntityConverter构建一个RequestEntity标准 OAuth 2.0 访问令牌请求的表示形式。
但是,提供自定义Converter)将允许您扩展标准 Token Request 并添加自定义参数。
要仅自定义请求的参数,您可以提供OAuth2AuthorizationCodeGrantRequestEntityConverter.setParametersConverter()使用自定义Converter<OAuth2AuthorizationCodeGrantRequest, MultiValueMap<String, String>>以完全覆盖随请求发送的参数。这通常比构造RequestEntity径直。
如果您只想添加其他参数,则可以提供OAuth2AuthorizationCodeGrantRequestEntityConverter.addParametersConverter()使用自定义Converter<OAuth2AuthorizationCodeGrantRequest, MultiValueMap<String, String>>它构造一个聚合Converter. |
自定义Converter必须返回有效的RequestEntity预期的 OAuth 2.0 提供者理解的 OAuth 2.0 访问令牌请求的表示形式。 |
自定义访问令牌响应
另一方面,如果您需要自定义 Token Response 的后处理,则需要提供DefaultAuthorizationCodeTokenResponseClient.setRestOperations()使用自定义配置RestOperations.
默认的RestOperations配置如下:
-
Java
-
Kotlin
RestTemplate restTemplate = new RestTemplate(Arrays.asList(
new FormHttpMessageConverter(),
new OAuth2AccessTokenResponseHttpMessageConverter()));
restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());
val restTemplate = RestTemplate(listOf(
FormHttpMessageConverter(),
OAuth2AccessTokenResponseHttpMessageConverter()))
restTemplate.errorHandler = OAuth2ErrorResponseErrorHandler()
Spring MVCFormHttpMessageConverter是必需的,因为它在发送 OAuth 2.0 访问令牌请求时使用。 |
OAuth2AccessTokenResponseHttpMessageConverter是一个HttpMessageConverter以获取 OAuth 2.0 访问令牌响应。
您可以提供OAuth2AccessTokenResponseHttpMessageConverter.setAccessTokenResponseConverter()使用自定义Converter<Map<String, Object>, OAuth2AccessTokenResponse>用于将 OAuth 2.0 访问令牌响应参数转换为OAuth2AccessTokenResponse.
OAuth2ErrorResponseErrorHandler是一个ResponseErrorHandler可以处理 OAuth 2.0 错误,例如。400 错误请求。
它使用OAuth2ErrorHttpMessageConverter用于将 OAuth 2.0 错误参数转换为OAuth2Error.
无论您是否自定义DefaultAuthorizationCodeTokenResponseClient或提供您自己的OAuth2AccessTokenResponseClient,您需要对其进行配置,如以下示例所示:
-
Java
-
Kotlin
-
Xml
@EnableWebSecurity
public class OAuth2ClientSecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.oauth2Client(oauth2 -> oauth2
.authorizationCodeGrant(codeGrant -> codeGrant
.accessTokenResponseClient(this.accessTokenResponseClient())
...
)
);
return http.build();
}
}
@EnableWebSecurity
class OAuth2ClientSecurityConfig {
@Bean
open fun filterChain(http: HttpSecurity): SecurityFilterChain {
http {
oauth2Client {
authorizationCodeGrant {
accessTokenResponseClient = accessTokenResponseClient()
}
}
}
return http.build()
}
}
<http>
<oauth2-client>
<authorization-code-grant access-token-response-client-ref="accessTokenResponseClient"/>
</oauth2-client>
</http>
刷新令牌
| 请参阅 OAuth 2.0 授权框架,了解有关刷新令牌的更多详细信息。 |
刷新 Access Token
| 请参阅访问令牌请求/响应协议流程,了解刷新令牌授予。 |
的默认实现OAuth2AccessTokenResponseClient的 Refresh Token grant 为DefaultRefreshTokenTokenResponseClient,它使用RestOperations在 Authorization Server 的令牌端点刷新访问令牌时。
这DefaultRefreshTokenTokenResponseClient非常灵活,因为它允许您自定义令牌请求的预处理和/或令牌响应的后处理。
自定义 Access Token 请求
如果需要自定义 Token Request 的预处理,可以提供DefaultRefreshTokenTokenResponseClient.setRequestEntityConverter()使用自定义Converter<OAuth2RefreshTokenGrantRequest, RequestEntity<?>>.
默认实现OAuth2RefreshTokenGrantRequestEntityConverter构建一个RequestEntity标准 OAuth 2.0 访问令牌请求的表示形式。
但是,提供自定义Converter)将允许您扩展标准 Token Request 并添加自定义参数。
要仅自定义请求的参数,您可以提供OAuth2RefreshTokenGrantRequestEntityConverter.setParametersConverter()使用自定义Converter<OAuth2RefreshTokenGrantRequest, MultiValueMap<String, String>>以完全覆盖随请求发送的参数。这通常比构造RequestEntity径直。
如果您只想添加其他参数,则可以提供OAuth2RefreshTokenGrantRequestEntityConverter.addParametersConverter()使用自定义Converter<OAuth2RefreshTokenGrantRequest, MultiValueMap<String, String>>它构造一个聚合Converter. |
自定义Converter必须返回有效的RequestEntity预期的 OAuth 2.0 提供者理解的 OAuth 2.0 访问令牌请求的表示形式。 |
自定义访问令牌响应
另一方面,如果您需要自定义 Token Response 的后处理,则需要提供DefaultRefreshTokenTokenResponseClient.setRestOperations()使用自定义配置RestOperations.
默认的RestOperations配置如下:
-
Java
-
Kotlin
RestTemplate restTemplate = new RestTemplate(Arrays.asList(
new FormHttpMessageConverter(),
new OAuth2AccessTokenResponseHttpMessageConverter()));
restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());
val restTemplate = RestTemplate(listOf(
FormHttpMessageConverter(),
OAuth2AccessTokenResponseHttpMessageConverter()))
restTemplate.errorHandler = OAuth2ErrorResponseErrorHandler()
Spring MVCFormHttpMessageConverter是必需的,因为它在发送 OAuth 2.0 访问令牌请求时使用。 |
OAuth2AccessTokenResponseHttpMessageConverter是一个HttpMessageConverter以获取 OAuth 2.0 访问令牌响应。
您可以提供OAuth2AccessTokenResponseHttpMessageConverter.setAccessTokenResponseConverter()使用自定义Converter<Map<String, Object>, OAuth2AccessTokenResponse>用于将 OAuth 2.0 访问令牌响应参数转换为OAuth2AccessTokenResponse.
OAuth2ErrorResponseErrorHandler是一个ResponseErrorHandler可以处理 OAuth 2.0 错误,例如。400 错误请求。
它使用OAuth2ErrorHttpMessageConverter用于将 OAuth 2.0 错误参数转换为OAuth2Error.
无论您是否自定义DefaultRefreshTokenTokenResponseClient或提供您自己的OAuth2AccessTokenResponseClient,您需要对其进行配置,如以下示例所示:
-
Java
-
Kotlin
// Customize
OAuth2AccessTokenResponseClient<OAuth2RefreshTokenGrantRequest> refreshTokenTokenResponseClient = ...
OAuth2AuthorizedClientProvider authorizedClientProvider =
OAuth2AuthorizedClientProviderBuilder.builder()
.authorizationCode()
.refreshToken(configurer -> configurer.accessTokenResponseClient(refreshTokenTokenResponseClient))
.build();
...
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
// Customize
val refreshTokenTokenResponseClient: OAuth2AccessTokenResponseClient<OAuth2RefreshTokenGrantRequest> = ...
val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
.authorizationCode()
.refreshToken { it.accessTokenResponseClient(refreshTokenTokenResponseClient) }
.build()
...
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
OAuth2AuthorizedClientProviderBuilder.builder().refreshToken()配置RefreshTokenOAuth2AuthorizedClientProvider,
它是OAuth2AuthorizedClientProvider对于 Refresh Token 授权。 |
这OAuth2RefreshToken可以选择在 Access Token Response 中返回authorization_code和password授权类型。
如果OAuth2AuthorizedClient.getRefreshToken()可用,并且OAuth2AuthorizedClient.getAccessToken()已过期,则会自动由RefreshTokenOAuth2AuthorizedClientProvider.
客户端凭证
| 请参阅 OAuth 2.0 授权框架,了解有关客户端凭证授予的更多详细信息。 |
申请 Access Token
| 请参阅访问令牌请求/响应协议流程,了解客户端凭证授予。 |
的默认实现OAuth2AccessTokenResponseClient对于 Client Credentials (客户端凭证) 授予为DefaultClientCredentialsTokenResponseClient,它使用RestOperations在 Authorization Server 的令牌端点请求访问令牌时。
这DefaultClientCredentialsTokenResponseClient非常灵活,因为它允许您自定义令牌请求的预处理和/或令牌响应的后处理。
自定义 Access Token 请求
如果需要自定义 Token Request 的预处理,可以提供DefaultClientCredentialsTokenResponseClient.setRequestEntityConverter()使用自定义Converter<OAuth2ClientCredentialsGrantRequest, RequestEntity<?>>.
默认实现OAuth2ClientCredentialsGrantRequestEntityConverter构建一个RequestEntity标准 OAuth 2.0 访问令牌请求的表示形式。
但是,提供自定义Converter)将允许您扩展标准 Token Request 并添加自定义参数。
要仅自定义请求的参数,您可以提供OAuth2ClientCredentialsGrantRequestEntityConverter.setParametersConverter()使用自定义Converter<OAuth2ClientCredentialsGrantRequest, MultiValueMap<String, String>>以完全覆盖随请求发送的参数。这通常比构造RequestEntity径直。
如果您只想添加其他参数,则可以提供OAuth2ClientCredentialsGrantRequestEntityConverter.addParametersConverter()使用自定义Converter<OAuth2ClientCredentialsGrantRequest, MultiValueMap<String, String>>它构造一个聚合Converter. |
自定义Converter必须返回有效的RequestEntity预期的 OAuth 2.0 提供者理解的 OAuth 2.0 访问令牌请求的表示形式。 |
自定义访问令牌响应
另一方面,如果您需要自定义 Token Response 的后处理,则需要提供DefaultClientCredentialsTokenResponseClient.setRestOperations()使用自定义配置RestOperations.
默认的RestOperations配置如下:
-
Java
-
Kotlin
RestTemplate restTemplate = new RestTemplate(Arrays.asList(
new FormHttpMessageConverter(),
new OAuth2AccessTokenResponseHttpMessageConverter()));
restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());
val restTemplate = RestTemplate(listOf(
FormHttpMessageConverter(),
OAuth2AccessTokenResponseHttpMessageConverter()))
restTemplate.errorHandler = OAuth2ErrorResponseErrorHandler()
Spring MVCFormHttpMessageConverter是必需的,因为它在发送 OAuth 2.0 访问令牌请求时使用。 |
OAuth2AccessTokenResponseHttpMessageConverter是一个HttpMessageConverter以获取 OAuth 2.0 访问令牌响应。
您可以提供OAuth2AccessTokenResponseHttpMessageConverter.setAccessTokenResponseConverter()使用自定义Converter<Map<String, Object>, OAuth2AccessTokenResponse>用于将 OAuth 2.0 访问令牌响应参数转换为OAuth2AccessTokenResponse.
OAuth2ErrorResponseErrorHandler是一个ResponseErrorHandler可以处理 OAuth 2.0 错误,例如。400 错误请求。
它使用OAuth2ErrorHttpMessageConverter用于将 OAuth 2.0 错误参数转换为OAuth2Error.
无论您是否自定义DefaultClientCredentialsTokenResponseClient或提供您自己的OAuth2AccessTokenResponseClient,您需要对其进行配置,如以下示例所示:
-
Java
-
Kotlin
// Customize
OAuth2AccessTokenResponseClient<OAuth2ClientCredentialsGrantRequest> clientCredentialsTokenResponseClient = ...
OAuth2AuthorizedClientProvider authorizedClientProvider =
OAuth2AuthorizedClientProviderBuilder.builder()
.clientCredentials(configurer -> configurer.accessTokenResponseClient(clientCredentialsTokenResponseClient))
.build();
...
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
// Customize
val clientCredentialsTokenResponseClient: OAuth2AccessTokenResponseClient<OAuth2ClientCredentialsGrantRequest> = ...
val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
.clientCredentials { it.accessTokenResponseClient(clientCredentialsTokenResponseClient) }
.build()
...
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
OAuth2AuthorizedClientProviderBuilder.builder().clientCredentials()配置ClientCredentialsOAuth2AuthorizedClientProvider,
它是OAuth2AuthorizedClientProvider的 Client Credentials grant(客户端凭证)授予。 |
使用 Access Token
给定 OAuth 2.0 客户端注册的以下 Spring Boot 2.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
…和OAuth2AuthorizedClientManager @Bean:
-
Java
-
Kotlin
@Bean
public OAuth2AuthorizedClientManager authorizedClientManager(
ClientRegistrationRepository clientRegistrationRepository,
OAuth2AuthorizedClientRepository authorizedClientRepository) {
OAuth2AuthorizedClientProvider authorizedClientProvider =
OAuth2AuthorizedClientProviderBuilder.builder()
.clientCredentials()
.build();
DefaultOAuth2AuthorizedClientManager authorizedClientManager =
new DefaultOAuth2AuthorizedClientManager(
clientRegistrationRepository, authorizedClientRepository);
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
return authorizedClientManager;
}
@Bean
fun authorizedClientManager(
clientRegistrationRepository: ClientRegistrationRepository,
authorizedClientRepository: OAuth2AuthorizedClientRepository): OAuth2AuthorizedClientManager {
val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
.clientCredentials()
.build()
val authorizedClientManager = DefaultOAuth2AuthorizedClientManager(
clientRegistrationRepository, authorizedClientRepository)
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
return authorizedClientManager
}
您可以获取OAuth2AccessToken如下:
-
Java
-
Kotlin
@Controller
public class OAuth2ClientController {
@Autowired
private OAuth2AuthorizedClientManager authorizedClientManager;
@GetMapping("/")
public String index(Authentication authentication,
HttpServletRequest servletRequest,
HttpServletResponse servletResponse) {
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
.principal(authentication)
.attributes(attrs -> {
attrs.put(HttpServletRequest.class.getName(), servletRequest);
attrs.put(HttpServletResponse.class.getName(), servletResponse);
})
.build();
OAuth2AuthorizedClient authorizedClient = this.authorizedClientManager.authorize(authorizeRequest);
OAuth2AccessToken accessToken = authorizedClient.getAccessToken();
...
return "index";
}
}
class OAuth2ClientController {
@Autowired
private lateinit var authorizedClientManager: OAuth2AuthorizedClientManager
@GetMapping("/")
fun index(authentication: Authentication?,
servletRequest: HttpServletRequest,
servletResponse: HttpServletResponse): String {
val authorizeRequest: OAuth2AuthorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
.principal(authentication)
.attributes(Consumer { attrs: MutableMap<String, Any> ->
attrs[HttpServletRequest::class.java.name] = servletRequest
attrs[HttpServletResponse::class.java.name] = servletResponse
})
.build()
val authorizedClient = authorizedClientManager.authorize(authorizeRequest)
val accessToken: OAuth2AccessToken = authorizedClient.accessToken
...
return "index"
}
}
HttpServletRequest和HttpServletResponse都是 OPTIONAL 属性。
如果未提供,它将默认为ServletRequestAttributes用RequestContextHolder.getRequestAttributes(). |
资源所有者密码凭证
| 请参阅 OAuth 2.0 授权框架,了解有关资源所有者密码凭证授予的更多详细信息。 |
申请 Access Token
| 请参阅访问令牌请求/响应协议流程,了解资源所有者密码凭证授予。 |
的默认实现OAuth2AccessTokenResponseClient对于 Resource Owner Password Credentials,grant 为DefaultPasswordTokenResponseClient,它使用RestOperations在 Authorization Server 的令牌端点请求访问令牌时。
这DefaultPasswordTokenResponseClient非常灵活,因为它允许您自定义令牌请求的预处理和/或令牌响应的后处理。
自定义 Access Token 请求
如果需要自定义 Token Request 的预处理,可以提供DefaultPasswordTokenResponseClient.setRequestEntityConverter()使用自定义Converter<OAuth2PasswordGrantRequest, RequestEntity<?>>.
默认实现OAuth2PasswordGrantRequestEntityConverter构建一个RequestEntity标准 OAuth 2.0 访问令牌请求的表示形式。
但是,提供自定义Converter)将允许您扩展标准 Token Request 并添加自定义参数。
要仅自定义请求的参数,您可以提供OAuth2PasswordGrantRequestEntityConverter.setParametersConverter()使用自定义Converter<OAuth2PasswordGrantRequest, MultiValueMap<String, String>>以完全覆盖随请求发送的参数。这通常比构造RequestEntity径直。
如果您只想添加其他参数,则可以提供OAuth2PasswordGrantRequestEntityConverter.addParametersConverter()使用自定义Converter<OAuth2PasswordGrantRequest, MultiValueMap<String, String>>它构造一个聚合Converter. |
自定义Converter必须返回有效的RequestEntity预期的 OAuth 2.0 提供者理解的 OAuth 2.0 访问令牌请求的表示形式。 |
自定义访问令牌响应
另一方面,如果您需要自定义 Token Response 的后处理,则需要提供DefaultPasswordTokenResponseClient.setRestOperations()使用自定义配置RestOperations.
默认的RestOperations配置如下:
-
Java
-
Kotlin
RestTemplate restTemplate = new RestTemplate(Arrays.asList(
new FormHttpMessageConverter(),
new OAuth2AccessTokenResponseHttpMessageConverter()));
restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());
val restTemplate = RestTemplate(listOf(
FormHttpMessageConverter(),
OAuth2AccessTokenResponseHttpMessageConverter()))
restTemplate.errorHandler = OAuth2ErrorResponseErrorHandler()
Spring MVCFormHttpMessageConverter是必需的,因为它在发送 OAuth 2.0 访问令牌请求时使用。 |
OAuth2AccessTokenResponseHttpMessageConverter是一个HttpMessageConverter以获取 OAuth 2.0 访问令牌响应。
您可以提供OAuth2AccessTokenResponseHttpMessageConverter.setAccessTokenResponseConverter()使用自定义Converter<Map<String, Object>, OAuth2AccessTokenResponse>用于将 OAuth 2.0 访问令牌响应参数转换为OAuth2AccessTokenResponse.
OAuth2ErrorResponseErrorHandler是一个ResponseErrorHandler可以处理 OAuth 2.0 错误,例如。400 错误请求。
它使用OAuth2ErrorHttpMessageConverter用于将 OAuth 2.0 错误参数转换为OAuth2Error.
无论您是否自定义DefaultPasswordTokenResponseClient或提供您自己的OAuth2AccessTokenResponseClient,您需要对其进行配置,如以下示例所示:
-
Java
-
Kotlin
// Customize
OAuth2AccessTokenResponseClient<OAuth2PasswordGrantRequest> passwordTokenResponseClient = ...
OAuth2AuthorizedClientProvider authorizedClientProvider =
OAuth2AuthorizedClientProviderBuilder.builder()
.password(configurer -> configurer.accessTokenResponseClient(passwordTokenResponseClient))
.refreshToken()
.build();
...
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
val passwordTokenResponseClient: OAuth2AccessTokenResponseClient<OAuth2PasswordGrantRequest> = ...
val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
.password { it.accessTokenResponseClient(passwordTokenResponseClient) }
.refreshToken()
.build()
...
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
OAuth2AuthorizedClientProviderBuilder.builder().password()配置PasswordOAuth2AuthorizedClientProvider,
它是OAuth2AuthorizedClientProvider对于 Resource Owner Password Credentials (资源所有者密码凭证) 授予。 |
使用 Access Token
给定 OAuth 2.0 客户端注册的以下 Spring Boot 2.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
…和OAuth2AuthorizedClientManager @Bean:
-
Java
-
Kotlin
@Bean
public OAuth2AuthorizedClientManager authorizedClientManager(
ClientRegistrationRepository clientRegistrationRepository,
OAuth2AuthorizedClientRepository authorizedClientRepository) {
OAuth2AuthorizedClientProvider authorizedClientProvider =
OAuth2AuthorizedClientProviderBuilder.builder()
.password()
.refreshToken()
.build();
DefaultOAuth2AuthorizedClientManager authorizedClientManager =
new DefaultOAuth2AuthorizedClientManager(
clientRegistrationRepository, authorizedClientRepository);
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
// Assuming the `username` and `password` are supplied as `HttpServletRequest` parameters,
// map the `HttpServletRequest` parameters to `OAuth2AuthorizationContext.getAttributes()`
authorizedClientManager.setContextAttributesMapper(contextAttributesMapper());
return authorizedClientManager;
}
private Function<OAuth2AuthorizeRequest, Map<String, Object>> contextAttributesMapper() {
return authorizeRequest -> {
Map<String, Object> contextAttributes = Collections.emptyMap();
HttpServletRequest servletRequest = authorizeRequest.getAttribute(HttpServletRequest.class.getName());
String username = servletRequest.getParameter(OAuth2ParameterNames.USERNAME);
String password = servletRequest.getParameter(OAuth2ParameterNames.PASSWORD);
if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
contextAttributes = new HashMap<>();
// `PasswordOAuth2AuthorizedClientProvider` requires both attributes
contextAttributes.put(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, username);
contextAttributes.put(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, password);
}
return contextAttributes;
};
}
@Bean
fun authorizedClientManager(
clientRegistrationRepository: ClientRegistrationRepository,
authorizedClientRepository: OAuth2AuthorizedClientRepository): OAuth2AuthorizedClientManager {
val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
.password()
.refreshToken()
.build()
val authorizedClientManager = DefaultOAuth2AuthorizedClientManager(
clientRegistrationRepository, authorizedClientRepository)
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
// Assuming the `username` and `password` are supplied as `HttpServletRequest` parameters,
// map the `HttpServletRequest` parameters to `OAuth2AuthorizationContext.getAttributes()`
authorizedClientManager.setContextAttributesMapper(contextAttributesMapper())
return authorizedClientManager
}
private fun contextAttributesMapper(): Function<OAuth2AuthorizeRequest, MutableMap<String, Any>> {
return Function { authorizeRequest ->
var contextAttributes: MutableMap<String, Any> = mutableMapOf()
val servletRequest: HttpServletRequest = authorizeRequest.getAttribute(HttpServletRequest::class.java.name)
val username = servletRequest.getParameter(OAuth2ParameterNames.USERNAME)
val password = servletRequest.getParameter(OAuth2ParameterNames.PASSWORD)
if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
contextAttributes = hashMapOf()
// `PasswordOAuth2AuthorizedClientProvider` requires both attributes
contextAttributes[OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME] = username
contextAttributes[OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME] = password
}
contextAttributes
}
}
您可以获取OAuth2AccessToken如下:
-
Java
-
Kotlin
@Controller
public class OAuth2ClientController {
@Autowired
private OAuth2AuthorizedClientManager authorizedClientManager;
@GetMapping("/")
public String index(Authentication authentication,
HttpServletRequest servletRequest,
HttpServletResponse servletResponse) {
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
.principal(authentication)
.attributes(attrs -> {
attrs.put(HttpServletRequest.class.getName(), servletRequest);
attrs.put(HttpServletResponse.class.getName(), servletResponse);
})
.build();
OAuth2AuthorizedClient authorizedClient = this.authorizedClientManager.authorize(authorizeRequest);
OAuth2AccessToken accessToken = authorizedClient.getAccessToken();
...
return "index";
}
}
@Controller
class OAuth2ClientController {
@Autowired
private lateinit var authorizedClientManager: OAuth2AuthorizedClientManager
@GetMapping("/")
fun index(authentication: Authentication?,
servletRequest: HttpServletRequest,
servletResponse: HttpServletResponse): String {
val authorizeRequest: OAuth2AuthorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
.principal(authentication)
.attributes(Consumer {
it[HttpServletRequest::class.java.name] = servletRequest
it[HttpServletResponse::class.java.name] = servletResponse
})
.build()
val authorizedClient = authorizedClientManager.authorize(authorizeRequest)
val accessToken: OAuth2AccessToken = authorizedClient.accessToken
...
return "index"
}
}
HttpServletRequest和HttpServletResponse都是 OPTIONAL 属性。
如果未提供,它将默认为ServletRequestAttributes用RequestContextHolder.getRequestAttributes(). |
JWT 持有者
| 有关 JWT 不记名授权的更多详细信息,请参阅 OAuth 2.0 客户端身份验证和授权的 JSON Web 令牌 (JWT) 配置文件。 |
申请 Access Token
| 请参阅 JWT Bearer 授权的访问令牌请求/响应协议流程。 |
的默认实现OAuth2AccessTokenResponseClient对于 JWT Bearer 授权为DefaultJwtBearerTokenResponseClient,它使用RestOperations在 Authorization Server 的令牌端点请求访问令牌时。
这DefaultJwtBearerTokenResponseClient非常灵活,因为它允许您自定义令牌请求的预处理和/或令牌响应的后处理。
自定义 Access Token 请求
如果需要自定义 Token Request 的预处理,可以提供DefaultJwtBearerTokenResponseClient.setRequestEntityConverter()使用自定义Converter<JwtBearerGrantRequest, RequestEntity<?>>.
默认实现JwtBearerGrantRequestEntityConverter构建一个RequestEntityOAuth 2.0 访问令牌请求的表示形式。
但是,提供自定义Converter,将允许您扩展 Token Request 并添加自定义参数。
要仅自定义请求的参数,您可以提供JwtBearerGrantRequestEntityConverter.setParametersConverter()使用自定义Converter<JwtBearerGrantRequest, MultiValueMap<String, String>>以完全覆盖随请求发送的参数。这通常比构造RequestEntity径直。
如果您只想添加其他参数,则可以提供JwtBearerGrantRequestEntityConverter.addParametersConverter()使用自定义Converter<JwtBearerGrantRequest, MultiValueMap<String, String>>它构造一个聚合Converter. |
自定义访问令牌响应
另一方面,如果您需要自定义 Token Response 的后处理,则需要提供DefaultJwtBearerTokenResponseClient.setRestOperations()使用自定义配置RestOperations.
默认的RestOperations配置如下:
-
Java
-
Kotlin
RestTemplate restTemplate = new RestTemplate(Arrays.asList(
new FormHttpMessageConverter(),
new OAuth2AccessTokenResponseHttpMessageConverter()));
restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());
val restTemplate = RestTemplate(listOf(
FormHttpMessageConverter(),
OAuth2AccessTokenResponseHttpMessageConverter()))
restTemplate.errorHandler = OAuth2ErrorResponseErrorHandler()
Spring MVCFormHttpMessageConverter是必需的,因为它在发送 OAuth 2.0 访问令牌请求时使用。 |
OAuth2AccessTokenResponseHttpMessageConverter是一个HttpMessageConverter以获取 OAuth 2.0 访问令牌响应。
您可以提供OAuth2AccessTokenResponseHttpMessageConverter.setAccessTokenResponseConverter()使用自定义Converter<Map<String, Object>, OAuth2AccessTokenResponse>用于将 OAuth 2.0 访问令牌响应参数转换为OAuth2AccessTokenResponse.
OAuth2ErrorResponseErrorHandler是一个ResponseErrorHandler可以处理 OAuth 2.0 错误,例如。400 错误请求。
它使用OAuth2ErrorHttpMessageConverter用于将 OAuth 2.0 错误参数转换为OAuth2Error.
无论您是否自定义DefaultJwtBearerTokenResponseClient或提供您自己的OAuth2AccessTokenResponseClient,您需要对其进行配置,如以下示例所示:
-
Java
-
Kotlin
// Customize
OAuth2AccessTokenResponseClient<JwtBearerGrantRequest> jwtBearerTokenResponseClient = ...
JwtBearerOAuth2AuthorizedClientProvider jwtBearerAuthorizedClientProvider = new JwtBearerOAuth2AuthorizedClientProvider();
jwtBearerAuthorizedClientProvider.setAccessTokenResponseClient(jwtBearerTokenResponseClient);
OAuth2AuthorizedClientProvider authorizedClientProvider =
OAuth2AuthorizedClientProviderBuilder.builder()
.provider(jwtBearerAuthorizedClientProvider)
.build();
...
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
// Customize
val jwtBearerTokenResponseClient: OAuth2AccessTokenResponseClient<JwtBearerGrantRequest> = ...
val jwtBearerAuthorizedClientProvider = JwtBearerOAuth2AuthorizedClientProvider()
jwtBearerAuthorizedClientProvider.setAccessTokenResponseClient(jwtBearerTokenResponseClient);
val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
.provider(jwtBearerAuthorizedClientProvider)
.build()
...
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
使用 Access Token
给定 OAuth 2.0 客户端注册的以下 Spring Boot 2.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:
-
Java
-
Kotlin
@Bean
public OAuth2AuthorizedClientManager authorizedClientManager(
ClientRegistrationRepository clientRegistrationRepository,
OAuth2AuthorizedClientRepository authorizedClientRepository) {
JwtBearerOAuth2AuthorizedClientProvider jwtBearerAuthorizedClientProvider =
new JwtBearerOAuth2AuthorizedClientProvider();
OAuth2AuthorizedClientProvider authorizedClientProvider =
OAuth2AuthorizedClientProviderBuilder.builder()
.provider(jwtBearerAuthorizedClientProvider)
.build();
DefaultOAuth2AuthorizedClientManager authorizedClientManager =
new DefaultOAuth2AuthorizedClientManager(
clientRegistrationRepository, authorizedClientRepository);
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
return authorizedClientManager;
}
@Bean
fun authorizedClientManager(
clientRegistrationRepository: ClientRegistrationRepository,
authorizedClientRepository: OAuth2AuthorizedClientRepository): OAuth2AuthorizedClientManager {
val jwtBearerAuthorizedClientProvider = JwtBearerOAuth2AuthorizedClientProvider()
val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
.provider(jwtBearerAuthorizedClientProvider)
.build()
val authorizedClientManager = DefaultOAuth2AuthorizedClientManager(
clientRegistrationRepository, authorizedClientRepository)
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
return authorizedClientManager
}
您可以获取OAuth2AccessToken如下:
-
Java
-
Kotlin
@RestController
public class OAuth2ResourceServerController {
@Autowired
private OAuth2AuthorizedClientManager authorizedClientManager;
@GetMapping("/resource")
public String resource(JwtAuthenticationToken jwtAuthentication) {
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
.principal(jwtAuthentication)
.build();
OAuth2AuthorizedClient authorizedClient = this.authorizedClientManager.authorize(authorizeRequest);
OAuth2AccessToken accessToken = authorizedClient.getAccessToken();
...
}
}
class OAuth2ResourceServerController {
@Autowired
private lateinit var authorizedClientManager: OAuth2AuthorizedClientManager
@GetMapping("/resource")
fun resource(jwtAuthentication: JwtAuthenticationToken?): String {
val authorizeRequest: OAuth2AuthorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
.principal(jwtAuthentication)
.build()
val authorizedClient = authorizedClientManager.authorize(authorizeRequest)
val accessToken: OAuth2AccessToken = authorizedClient.accessToken
...
}
}
JwtBearerOAuth2AuthorizedClientProvider解决Jwtassertion viaOAuth2AuthorizationContext.getPrincipal().getPrincipal()默认情况下,因此使用JwtAuthenticationToken在前面的示例中。 |
如果您需要解决Jwtassertion 的 Assertion 中,您可以提供JwtBearerOAuth2AuthorizedClientProvider.setJwtAssertionResolver()使用自定义Function<OAuth2AuthorizationContext, Jwt>. |