# 授权赠款支助

# 授权代码

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

# 获得授权

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

# 发起授权请求

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

OAuth2AuthorizationRequestResolver的主要作用是从提供的Web请求中解析OAuth2AuthorizationRequest。默认实现DefaultOAuth2AuthorizationRequestResolver在(默认)路径/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的请求将启动由OAuth2AuthorizationRequestRedirectFilter重定向的授权请求,并最终启动授权代码授予流。

AuthorizationCodeOAuth2AuthorizedClientProvider是用于授权代码授予的OAuth2AuthorizedClientProvider的实现,
还通过OAuth2AuthorizationRequestRedirectFilter发起重定向的授权请求。

如果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

DefaultOAuth2AuthorizationRequestResolver还支持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客户端运行在代理服务器后面时,使用URI模板变量配置redirect-uri模板变量特别有用。这确保了在展开redirect-uri时使用X-Forwarded-*头。

# 自定义授权请求

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

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

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

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

Java

@EnableWebSecurity
public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {

	@Autowired
	private ClientRegistrationRepository clientRegistrationRepository;

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
			.authorizeHttpRequests(authorize -> authorize
				.anyRequest().authenticated()
			)
			.oauth2Login(oauth2 -> oauth2
				.authorizationEndpoint(authorization -> authorization
					.authorizationRequestResolver(
						authorizationRequestResolver(this.clientRegistrationRepository)
					)
				)
			);
	}

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

Kotlin

@EnableWebSecurity
class SecurityConfig : WebSecurityConfigurerAdapter() {

    @Autowired
    private lateinit var customClientRegistrationRepository: ClientRegistrationRepository

    override fun configure(http: HttpSecurity) {
        http {
            authorizeRequests {
                authorize(anyRequest, authenticated)
            }
            oauth2Login {
                authorizationEndpoint {
                    authorizationRequestResolver = authorizationRequestResolver(customClientRegistrationRepository)
                }
            }
        }
    }

    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属性中添加它。

例如,如果请求参数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

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()
                }
    }
}

# 存储授权请求

从发起授权请求到接收授权响应(回调),AuthorizationRequestRepository负责OAuth2AuthorizationRequest的持久性。

OAuth2AuthorizationRequest用于关联和验证授权响应。

AuthorizationRequestRepository的默认实现是HttpSessionOAuth2AuthorizationRequestRepository,它将OAuth2AuthorizationRequest存储在HttpSession中。

如果你有AuthorizationRequestRepository的自定义实现,则可以按照以下示例对其进行配置:

例1. AuthorizationRequestRepository配置

Java

@EnableWebSecurity
public class OAuth2ClientSecurityConfig extends WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
			.oauth2Client(oauth2 -> oauth2
				.authorizationCodeGrant(codeGrant -> codeGrant
					.authorizationRequestRepository(this.authorizationRequestRepository())
					...
				)
			);
	}
}

Kotlin

@EnableWebSecurity
class OAuth2ClientSecurityConfig : WebSecurityConfigurerAdapter() {

    override fun configure(http: HttpSecurity) {
        http {
            oauth2Client {
                authorizationCodeGrant {
                    authorizationRequestRepository = authorizationRequestRepository()
                }
            }
        }
    }
}

XML

<http>
	<oauth2-client>
		<authorization-code-grant authorization-request-repository-ref="authorizationRequestRepository"/>
	</oauth2-client>
</http>

# 请求访问令牌

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

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

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

# 自定义访问令牌请求

如果需要定制令牌请求的预处理,则可以提供带有自定义DefaultAuthorizationCodeTokenResponseClient.setRequestEntityConverter()Converter<OAuth2AuthorizationCodeGrantRequest, RequestEntity<?>>。默认的实现OAuth2AuthorizationCodeGrantRequestEntityConverter构建了标准RequestEntity表示法OAuth2.0访问令牌请求 (opens new window)。但是,提供一个自定义Converter,将允许你扩展标准令牌请求并添加自定义参数。

要仅自定义请求的参数,可以为OAuth2AuthorizationCodeGrantRequestEntityConverter.setParametersConverter()提供自定义的Converter<OAuth2AuthorizationCodeGrantRequest, MultiValueMap<String, String>>,以完全覆盖随请求发送的参数。这通常比直接构造RequestEntity更简单。

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

# 自定义访问令牌响应

在另一端,如果需要自定义令牌响应的后处理,则需要为DefaultAuthorizationCodeTokenResponseClient.setRestOperations()提供自定义配置的RestOperations。默认的RestOperations配置如下:

Java

RestTemplate restTemplate = new RestTemplate(Arrays.asList(
		new FormHttpMessageConverter(),
		new OAuth2AccessTokenResponseHttpMessageConverter()));

restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());

Kotlin

val restTemplate = RestTemplate(listOf(
        FormHttpMessageConverter(),
        OAuth2AccessTokenResponseHttpMessageConverter()))

restTemplate.errorHandler = OAuth2ErrorResponseErrorHandler()
Spring 在发送OAuth2.0访问令牌请求时,需要使用MVC。

OAuth2AccessTokenResponseHttpMessageConverter是用于OAuth2.0访问令牌响应的HttpMessageConverter。你可以为OAuth2AccessTokenResponseHttpMessageConverter.setAccessTokenResponseConverter()提供一个自定义的Converter<Map<String, Object>, OAuth2AccessTokenResponse>,用于将OAuth2.0访问令牌响应参数转换为OAuth2AccessTokenResponse

OAuth2ErrorResponseErrorHandler是一个ResponseErrorHandler,它可以处理OAuth2.0错误,例如400BAD请求。它使用OAuth2ErrorHttpMessageConverter将OAuth2.0错误参数转换为OAuth2Error

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

例2.访问令牌响应配置

Java

@EnableWebSecurity
public class OAuth2ClientSecurityConfig extends WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
			.oauth2Client(oauth2 -> oauth2
				.authorizationCodeGrant(codeGrant -> codeGrant
					.accessTokenResponseClient(this.accessTokenResponseClient())
					...
				)
			);
	}
}

Kotlin

@EnableWebSecurity
class OAuth2ClientSecurityConfig : WebSecurityConfigurerAdapter() {

    override fun configure(http: HttpSecurity) {
        http {
            oauth2Client {
                authorizationCodeGrant {
                    accessTokenResponseClient = accessTokenResponseClient()
                }
            }
        }
    }
}

XML

<http>
	<oauth2-client>
		<authorization-code-grant access-token-response-client-ref="accessTokenResponseClient"/>
	</oauth2-client>
</http>

# 刷新令牌

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

# 刷新访问令牌

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

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

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

# 自定义访问令牌请求

如果需要对令牌请求的预处理进行自定义,则可以提供带有自定义DefaultRefreshTokenTokenResponseClient.setRequestEntityConverter()Converter<OAuth2RefreshTokenGrantRequest, RequestEntity<?>>。默认的实现OAuth2RefreshTokenGrantRequestEntityConverter构建了标准RequestEntity表示法OAuth2.0访问令牌请求 (opens new window)。但是,提供一个自定义Converter,将允许你扩展标准令牌请求并添加自定义参数。

要仅自定义请求的参数,可以为OAuth2RefreshTokenGrantRequestEntityConverter.setParametersConverter()提供自定义的Converter<OAuth2RefreshTokenGrantRequest, MultiValueMap<String, String>>,以完全覆盖随请求发送的参数。这通常比直接构造RequestEntity更简单。

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

# 自定义访问令牌响应

在另一端,如果需要自定义令牌响应的后处理,则需要为DefaultRefreshTokenTokenResponseClient.setRestOperations()提供自定义配置的RestOperations。默认的RestOperations配置如下:

Java

RestTemplate restTemplate = new RestTemplate(Arrays.asList(
		new FormHttpMessageConverter(),
		new OAuth2AccessTokenResponseHttpMessageConverter()));

restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());

Kotlin

val restTemplate = RestTemplate(listOf(
        FormHttpMessageConverter(),
        OAuth2AccessTokenResponseHttpMessageConverter()))

restTemplate.errorHandler = OAuth2ErrorResponseErrorHandler()
Spring 在发送OAuth2.0访问令牌请求时,需要使用MVC。

OAuth2AccessTokenResponseHttpMessageConverter是用于OAuth2.0访问令牌响应的HttpMessageConverter。你可以为OAuth2AccessTokenResponseHttpMessageConverter.setAccessTokenResponseConverter()提供一个自定义Converter<Map<String, Object>, OAuth2AccessTokenResponse>,用于将OAuth2.0访问令牌响应参数转换为OAuth2AccessTokenResponse

OAuth2ErrorResponseErrorHandler是一个ResponseErrorHandler,它可以处理OAuth2.0错误,例如400BAD请求。它使用OAuth2ErrorHttpMessageConverter将OAuth2.0错误参数转换为OAuth2Error

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

Java

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

OAuth2AuthorizedClientProvider authorizedClientProvider =
		OAuth2AuthorizedClientProviderBuilder.builder()
				.authorizationCode()
				.refreshToken(configurer -> configurer.accessTokenResponseClient(refreshTokenTokenResponseClient))
				.build();

...

authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);

Kotlin

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

val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
        .authorizationCode()
        .refreshToken { it.accessTokenResponseClient(refreshTokenTokenResponseClient) }
        .build()

...

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

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

# 客户凭据

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

# 请求访问令牌

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

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

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

# 自定义访问令牌请求

如果需要定制令牌请求的预处理,则可以提供带有自定义DefaultClientCredentialsTokenResponseClient.setRequestEntityConverter()Converter<OAuth2ClientCredentialsGrantRequest, RequestEntity<?>>。默认的实现OAuth2ClientCredentialsGrantRequestEntityConverter构建了标准RequestEntity表示法OAuth2.0访问令牌请求 (opens new window)。但是,提供一个自定义Converter,将允许你扩展标准令牌请求并添加自定义参数。

要仅自定义请求的参数,可以为OAuth2ClientCredentialsGrantRequestEntityConverter.setParametersConverter()提供自定义的Converter<OAuth2ClientCredentialsGrantRequest, MultiValueMap<String, String>>,以完全覆盖随请求发送的参数。这通常比直接构造RequestEntity更简单。

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

# 自定义访问令牌响应

在另一端,如果需要自定义令牌响应的后处理,则需要为DefaultClientCredentialsTokenResponseClient.setRestOperations()提供自定义配置的RestOperations。默认的RestOperations配置如下:

Java

RestTemplate restTemplate = new RestTemplate(Arrays.asList(
		new FormHttpMessageConverter(),
		new OAuth2AccessTokenResponseHttpMessageConverter()));

restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());

Kotlin

val restTemplate = RestTemplate(listOf(
        FormHttpMessageConverter(),
        OAuth2AccessTokenResponseHttpMessageConverter()))

restTemplate.errorHandler = OAuth2ErrorResponseErrorHandler()
Spring 在发送OAuth2.0访问令牌请求时,需要使用MVC。

OAuth2AccessTokenResponseHttpMessageConverter是用于OAuth2.0访问令牌响应的HttpMessageConverter。你可以为OAuth2AccessTokenResponseHttpMessageConverter.setAccessTokenResponseConverter()提供一个自定义的Converter<Map<String, Object>, OAuth2AccessTokenResponse>,用于将OAuth2.0访问令牌响应参数转换为OAuth2AccessTokenResponse

OAuth2ErrorResponseErrorHandler是一个ResponseErrorHandler,它可以处理OAuth2.0错误,例如400BAD请求。它使用OAuth2ErrorHttpMessageConverter将OAuth2.0错误参数转换为OAuth2Error

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

Java

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

OAuth2AuthorizedClientProvider authorizedClientProvider =
		OAuth2AuthorizedClientProviderBuilder.builder()
				.clientCredentials(configurer -> configurer.accessTokenResponseClient(clientCredentialsTokenResponseClient))
				.build();

...

authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);

Kotlin

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

val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
        .clientCredentials { it.accessTokenResponseClient(clientCredentialsTokenResponseClient) }
        .build()

...

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

# 使用访问令牌

给出了用于OAuth2.0客户端注册的以下 Spring 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

…和OAuth2AuthorizedClientManager``@Bean:

Java

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

Kotlin

@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

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

Kotlin

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"
    }
}
HttpServletRequestHttpServletResponse都是可选属性。
如果不提供,它将默认为ServletRequestAttributes使用RequestContextHolder.getRequestAttributes()

# 资源所有者密码凭据

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

# 请求访问令牌

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

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

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

# 自定义访问令牌请求

如果需要定制令牌请求的预处理,则可以提供带有自定义DefaultPasswordTokenResponseClient.setRequestEntityConverter()Converter<OAuth2PasswordGrantRequest, RequestEntity<?>>。默认的实现OAuth2PasswordGrantRequestEntityConverter构建了标准RequestEntity表示法OAuth2.0访问令牌请求 (opens new window)。但是,提供一个自定义Converter,将允许你扩展标准令牌请求并添加自定义参数。

要仅自定义请求的参数,可以为OAuth2PasswordGrantRequestEntityConverter.setParametersConverter()提供自定义的Converter<OAuth2PasswordGrantRequest, MultiValueMap<String, String>>,以完全覆盖随请求发送的参数。这通常比直接构造RequestEntity更简单。

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

# 自定义访问令牌响应

在另一端,如果需要自定义令牌响应的后处理,则需要为DefaultPasswordTokenResponseClient.setRestOperations()提供自定义配置的RestOperations。默认的RestOperations配置如下:

Java

RestTemplate restTemplate = new RestTemplate(Arrays.asList(
		new FormHttpMessageConverter(),
		new OAuth2AccessTokenResponseHttpMessageConverter()));

restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());

Kotlin

val restTemplate = RestTemplate(listOf(
        FormHttpMessageConverter(),
        OAuth2AccessTokenResponseHttpMessageConverter()))

restTemplate.errorHandler = OAuth2ErrorResponseErrorHandler()
Spring 在发送OAuth2.0访问令牌请求时,需要使用MVC。

OAuth2AccessTokenResponseHttpMessageConverter是用于OAuth2.0访问令牌响应的HttpMessageConverter。你可以为OAuth2AccessTokenResponseHttpMessageConverter.setAccessTokenResponseConverter()提供一个自定义的Converter<Map<String, Object>, OAuth2AccessTokenResponse>,用于将OAuth2.0访问令牌响应参数转换为OAuth2AccessTokenResponse

OAuth2ErrorResponseErrorHandler是一个ResponseErrorHandler,它可以处理OAuth2.0错误,例如400BAD请求。它使用OAuth2ErrorHttpMessageConverter将OAuth2.0错误参数转换为OAuth2Error

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

Java

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

OAuth2AuthorizedClientProvider authorizedClientProvider =
		OAuth2AuthorizedClientProviderBuilder.builder()
				.password(configurer -> configurer.accessTokenResponseClient(passwordTokenResponseClient))
				.refreshToken()
				.build();

...

authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);

Kotlin

val passwordTokenResponseClient: OAuth2AccessTokenResponseClient<OAuth2PasswordGrantRequest> = ...

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

...

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

# 使用访问令牌

给出了用于OAuth2.0客户端注册的以下 Spring 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

…和OAuth2AuthorizedClientManager``@Bean:

Java

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

Kotlin

@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

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

Kotlin

@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"
    }
}
HttpServletRequestHttpServletResponse都是可选属性。
如果不提供,它将默认为ServletRequestAttributes使用RequestContextHolder.getRequestAttributes()

# JWT持有人

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

# 请求访问令牌

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

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

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

# 自定义访问令牌请求

如果需要对令牌请求的预处理进行自定义,则可以提供带有自定义DefaultJwtBearerTokenResponseClient.setRequestEntityConverter()Converter<JwtBearerGrantRequest, RequestEntity<?>>。默认的实现JwtBearerGrantRequestEntityConverter构建了RequestEntity表示OAuth2.0访问令牌请求 (opens new window)。但是,提供一个自定义Converter,将允许你扩展令牌请求并添加自定义参数。

要仅自定义请求的参数,可以为JwtBearerGrantRequestEntityConverter.setParametersConverter()提供自定义的Converter<JwtBearerGrantRequest, MultiValueMap<String, String>>,以完全覆盖随请求发送的参数。这通常比直接构造RequestEntity更简单。

如果你只喜欢添加额外的参数,那么可以为JwtBearerGrantRequestEntityConverter.addParametersConverter()提供一个自定义的Converter<JwtBearerGrantRequest, MultiValueMap<String, String>>,它构造一个聚合Converter

# 自定义访问令牌响应

在另一端,如果需要自定义令牌响应的后处理,则需要为DefaultJwtBearerTokenResponseClient.setRestOperations()提供自定义配置的RestOperations。默认的RestOperations配置如下:

Java

RestTemplate restTemplate = new RestTemplate(Arrays.asList(
		new FormHttpMessageConverter(),
		new OAuth2AccessTokenResponseHttpMessageConverter()));

restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());

Kotlin

val restTemplate = RestTemplate(listOf(
        FormHttpMessageConverter(),
        OAuth2AccessTokenResponseHttpMessageConverter()))

restTemplate.errorHandler = OAuth2ErrorResponseErrorHandler()
Spring 在发送OAuth2.0访问令牌请求时,需要使用MVC。

OAuth2AccessTokenResponseHttpMessageConverter是用于OAuth2.0访问令牌响应的HttpMessageConverter。你可以为OAuth2AccessTokenResponseHttpMessageConverter.setAccessTokenResponseConverter()提供一个自定义的Converter<Map<String, Object>, OAuth2AccessTokenResponse>,用于将OAuth2.0访问令牌响应参数转换为OAuth2AccessTokenResponse

OAuth2ErrorResponseErrorHandler是一个ResponseErrorHandler,它可以处理OAuth2.0错误,例如400BAD请求。它使用OAuth2ErrorHttpMessageConverter将OAuth2.0错误参数转换为OAuth2Error

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

Java

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

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

OAuth2AuthorizedClientProvider authorizedClientProvider =
		OAuth2AuthorizedClientProviderBuilder.builder()
				.provider(jwtBearerAuthorizedClientProvider)
				.build();

...

authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);

Kotlin

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

val jwtBearerAuthorizedClientProvider = JwtBearerOAuth2AuthorizedClientProvider()
jwtBearerAuthorizedClientProvider.setAccessTokenResponseClient(jwtBearerTokenResponseClient);

val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.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:

Java

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

Kotlin

@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

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

		...

	}
}

Kotlin

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

        ...

    }
}

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