授權許可支援

本節描述 Spring Security 對授權許可的支援。

授權碼

關於授權碼許可的更多詳細資訊,請參閱 OAuth 2.0 授權框架。

取得授權

關於授權碼許可的授權請求/回應協定流程,請參閱 OAuth 2.0 授權框架。

啟動授權請求

OAuth2AuthorizationRequestRedirectFilter 使用 OAuth2AuthorizationRequestResolver 來解析 OAuth2AuthorizationRequest,並透過將終端使用者的使用者代理重新導向至授權伺服器的授權端點,來啟動授權碼許可流程。

OAuth2AuthorizationRequestResolver 的主要角色是從提供的網路請求解析 OAuth2AuthorizationRequest。預設實作 DefaultOAuth2AuthorizationRequestResolver 比對 (預設) 路徑 /oauth2/authorization/{registrationId},提取 registrationId,並使用它來為相關聯的 ClientRegistration 建構 OAuth2AuthorizationRequest

請考慮以下 OAuth 2.0 用戶端註冊的 Spring Boot 屬性

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 啟動授權請求重新導向。

如果 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) 來支援。如果用戶端在不受信任的環境 (例如原生應用程式或基於網路瀏覽器的應用程式) 中執行,因此無法維護其憑證的機密性,則在以下條件為真時會自動使用 PKCE

  1. client-secret 已省略 (或空白)

  2. client-authentication-method 設定為 none (ClientAuthenticationMethod.NONE)

如果 OAuth 2.0 提供者支援機密用戶端的 PKCE,您可以 (選擇性地) 使用 DefaultOAuth2AuthorizationRequestResolver.setAuthorizationRequestCustomizer(OAuth2AuthorizationRequestCustomizers.withPkce()) 進行組態。

DefaultOAuth2AuthorizationRequestResolver 也支援使用 UriComponentsBuilderredirect-uriURI 範本變數。

以下組態使用所有支援的 URI 範本變數

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

{baseUrl} 解析為 {baseScheme}://{baseHost}{basePort}{basePath}

當 OAuth 2.0 用戶端在Proxy 伺服器後方執行時,使用 URI 範本變數組態 redirect-uri 特別有用。這樣做可確保在擴展 redirect-uri 時使用 X-Forwarded-* 標頭。

自訂授權請求

OAuth2AuthorizationRequestResolver 可以實現的主要用例之一是能夠使用超出 OAuth 2.0 授權框架中定義的標準參數的額外參數來自訂授權請求。

例如,OpenID Connect 為授權碼流程定義了額外的 OAuth 2.0 請求參數,從 OAuth 2.0 授權框架中定義的標準參數擴展而來。其中一個擴展參數是 prompt 參數。

prompt 參數是可選的。以空格分隔、區分大小寫的 ASCII 字串值列表,用於指定授權伺服器是否提示終端使用者重新驗證和同意。定義的值為:noneloginconsentselect_account

以下範例展示如何使用 Consumer<OAuth2AuthorizationRequest.Builder> 組態 DefaultOAuth2AuthorizationRequestResolver,該消費者透過包含請求參數 prompt=consent,來自訂 oauth2Login() 的授權請求。

  • Java

  • Kotlin

@Configuration
@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"));
	}
}
@Configuration
@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 屬性中新增它。

例如,如果提供者 okta 的請求參數 prompt 的值始終為 consent,您可以如下組態它

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

先前的範例展示了在標準參數之上新增自訂參數的常見用例。或者,如果您的需求更進階,您可以透過覆寫 OAuth2AuthorizationRequest.authorizationRequestUri 屬性來完全控制建構授權請求 URI。

OAuth2AuthorizationRequest.Builder.build() 建構 OAuth2AuthorizationRequest.authorizationRequestUri,它表示授權請求 URI,包括使用 application/x-www-form-urlencoded 格式的所有查詢參數。

以下範例展示了先前範例中 authorizationRequestCustomizer() 的變體,而是覆寫 OAuth2AuthorizationRequest.authorizationRequestUri 屬性

  • Java

  • Kotlin

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

儲存授權請求

AuthorizationRequestRepository 負責從授權請求啟動到收到授權回應 (回呼) 的時間段內持久化 OAuth2AuthorizationRequest

OAuth2AuthorizationRequest 用於關聯和驗證授權回應。

AuthorizationRequestRepository 的預設實作是 HttpSessionOAuth2AuthorizationRequestRepository,它將 OAuth2AuthorizationRequest 儲存在 HttpSession 中。

如果您有 AuthorizationRequestRepository 的自訂實作,您可以如下組態它

AuthorizationRequestRepository 組態
  • Java

  • Kotlin

  • Xml

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

請求存取令牌

關於授權碼許可的存取令牌請求/回應協定流程,請參閱 OAuth 2.0 授權框架。

授權碼許可的 OAuth2AccessTokenResponseClient 的預設實作是 DefaultAuthorizationCodeTokenResponseClient,它使用 RestOperations 實例在授權伺服器的令牌端點交換授權碼以取得存取令牌。

DefaultAuthorizationCodeTokenResponseClient 很靈活,因為它允許您自訂令牌請求的預先處理和/或令牌回應的後續處理。

自訂存取令牌請求

如果您需要自訂令牌請求的預先處理,您可以為 DefaultAuthorizationCodeTokenResponseClient.setRequestEntityConverter() 提供自訂的 Converter<OAuth2AuthorizationCodeGrantRequest, RequestEntity<?>>。預設實作 (OAuth2AuthorizationCodeGrantRequestEntityConverter) 建構標準OAuth 2.0 存取令牌請求RequestEntity 表示。但是,提供自訂 Converter 將允許您擴展標準令牌請求並新增自訂參數。

若要僅自訂請求的參數,您可以為 OAuth2AuthorizationCodeGrantRequestEntityConverter.setParametersConverter() 提供自訂的 Converter<OAuth2AuthorizationCodeGrantRequest, MultiValueMap<String, String>>,以完全覆寫隨請求傳送的參數。這通常比直接建構 RequestEntity 更簡單。

如果您只想新增額外參數,您可以為 OAuth2AuthorizationCodeGrantRequestEntityConverter.addParametersConverter() 提供自訂的 Converter<OAuth2AuthorizationCodeGrantRequest, MultiValueMap<String, String>>,它會建構一個聚合 Converter

自訂 Converter 必須傳回 OAuth 2.0 存取令牌請求的有效 RequestEntity 表示,該請求可被目標 OAuth 2.0 提供者理解。

自訂存取令牌回應

另一方面,如果您需要自訂令牌回應的後續處理,您需要為 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 MVC FormHttpMessageConverter 是必要的,因為它在傳送 OAuth 2.0 存取令牌請求時使用。

OAuth2AccessTokenResponseHttpMessageConverter 是 OAuth 2.0 存取令牌回應的 HttpMessageConverter。您可以為 OAuth2AccessTokenResponseHttpMessageConverter.setAccessTokenResponseConverter() 提供自訂的 Converter<Map<String, Object>, OAuth2AccessTokenResponse>,用於將 OAuth 2.0 存取令牌回應參數轉換為 OAuth2AccessTokenResponse

OAuth2ErrorResponseErrorHandler 是一個 ResponseErrorHandler,可以處理 OAuth 2.0 錯誤,例如 400 Bad Request。它使用 OAuth2ErrorHttpMessageConverter 將 OAuth 2.0 錯誤參數轉換為 OAuth2Error

無論您自訂 DefaultAuthorizationCodeTokenResponseClient 還是提供您自己的 OAuth2AccessTokenResponseClient 實作,您都需要如下組態它

存取令牌回應組態
  • Java

  • Kotlin

  • Xml

@Configuration
@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();
	}
}
@Configuration
@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 授權框架。

重新整理存取令牌

關於重新整理令牌許可的存取令牌請求/回應協定流程,請參閱 OAuth 2.0 授權框架。

重新整理令牌許可的 OAuth2AccessTokenResponseClient 的預設實作是 DefaultRefreshTokenTokenResponseClient,它在授權伺服器的令牌端點重新整理存取令牌時使用 RestOperations

DefaultRefreshTokenTokenResponseClient 很靈活,因為它允許您自訂令牌請求的預先處理或令牌回應的後續處理。

自訂存取令牌請求

如果您需要自訂令牌請求的預先處理,您可以為 DefaultRefreshTokenTokenResponseClient.setRequestEntityConverter() 提供自訂的 Converter<OAuth2RefreshTokenGrantRequest, RequestEntity<?>>。預設實作 (OAuth2RefreshTokenGrantRequestEntityConverter) 建構標準OAuth 2.0 存取令牌請求RequestEntity 表示。但是,提供自訂 Converter 將允許您擴展標準令牌請求並新增自訂參數。

若要僅自訂請求的參數,您可以為 OAuth2RefreshTokenGrantRequestEntityConverter.setParametersConverter() 提供自訂的 Converter<OAuth2RefreshTokenGrantRequest, MultiValueMap<String, String>>,以完全覆寫隨請求傳送的參數。這通常比直接建構 RequestEntity 更簡單。

如果您只想新增額外參數,您可以為 OAuth2RefreshTokenGrantRequestEntityConverter.addParametersConverter() 提供自訂的 Converter<OAuth2RefreshTokenGrantRequest, MultiValueMap<String, String>>,它會建構一個聚合 Converter

自訂 Converter 必須傳回 OAuth 2.0 存取令牌請求的有效 RequestEntity 表示,該請求可被目標 OAuth 2.0 提供者理解。

自訂存取令牌回應

另一方面,如果您需要自訂令牌回應的後續處理,您需要為 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 MVC FormHttpMessageConverter 是必要的,因為它在傳送 OAuth 2.0 存取令牌請求時使用。

OAuth2AccessTokenResponseHttpMessageConverter 是 OAuth 2.0 存取令牌回應的 HttpMessageConverter。您可以為 OAuth2AccessTokenResponseHttpMessageConverter.setAccessTokenResponseConverter() 提供自訂的 Converter<Map<String, Object>, OAuth2AccessTokenResponse>,用於將 OAuth 2.0 存取令牌回應參數轉換為 OAuth2AccessTokenResponse

OAuth2ErrorResponseErrorHandler 是一個 ResponseErrorHandler,可以處理 OAuth 2.0 錯誤,例如 400 Bad Request。它使用 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 的實作。

OAuth2RefreshToken 可以選擇性地在 authorization_codepassword 許可類型的存取令牌回應中傳回。如果 OAuth2AuthorizedClient.getRefreshToken() 可用且 OAuth2AuthorizedClient.getAccessToken() 已過期,則會由 RefreshTokenOAuth2AuthorizedClientProvider 自動重新整理。

用戶端憑證

關於用戶端憑證許可的更多詳細資訊,請參閱 OAuth 2.0 授權框架。

請求存取令牌

關於用戶端憑證許可的更多詳細資訊,請參閱 OAuth 2.0 授權框架。

用戶端憑證許可的 OAuth2AccessTokenResponseClient 的預設實作是 DefaultClientCredentialsTokenResponseClient,它在授權伺服器的令牌端點請求存取令牌時使用 RestOperations

DefaultClientCredentialsTokenResponseClient 很靈活,因為它允許您自訂令牌請求的預先處理或令牌回應的後續處理。

自訂存取令牌請求

如果您需要自訂令牌請求的預先處理,您可以為 DefaultClientCredentialsTokenResponseClient.setRequestEntityConverter() 提供自訂的 Converter<OAuth2ClientCredentialsGrantRequest, RequestEntity<?>>。預設實作 (OAuth2ClientCredentialsGrantRequestEntityConverter) 建構標準OAuth 2.0 存取令牌請求RequestEntity 表示。但是,提供自訂 Converter 將允許您擴展標準令牌請求並新增自訂參數。

若要僅自訂請求的參數,您可以為 OAuth2ClientCredentialsGrantRequestEntityConverter.setParametersConverter() 提供自訂的 Converter<OAuth2ClientCredentialsGrantRequest, MultiValueMap<String, String>>,以完全覆寫隨請求傳送的參數。這通常比直接建構 RequestEntity 更簡單。

如果您只想新增額外參數,您可以為 OAuth2ClientCredentialsGrantRequestEntityConverter.addParametersConverter() 提供自訂的 Converter<OAuth2ClientCredentialsGrantRequest, MultiValueMap<String, String>>,它會建構一個聚合 Converter

自訂 Converter 必須傳回 OAuth 2.0 存取令牌請求的有效 RequestEntity 表示,該請求可被目標 OAuth 2.0 提供者理解。

自訂存取令牌回應

另一方面,如果您需要自訂令牌回應的後續處理,您需要為 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 MVC FormHttpMessageConverter 是必要的,因為它在傳送 OAuth 2.0 存取令牌請求時使用。

OAuth2AccessTokenResponseHttpMessageConverter 是 OAuth 2.0 存取令牌回應的 HttpMessageConverter。您可以為 OAuth2AccessTokenResponseHttpMessageConverter.setAccessTokenResponseConverter() 提供自訂的 Converter<Map<String, Object>, OAuth2AccessTokenResponse>,用於將 OAuth 2.0 存取令牌回應參數轉換為 OAuth2AccessTokenResponse

OAuth2ErrorResponseErrorHandler 是一個 ResponseErrorHandler,可以處理 OAuth 2.0 錯誤,例如 400 Bad Request。它使用 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 的實作。

使用存取令牌

請考慮以下 OAuth 2.0 用戶端註冊的 Spring Boot 屬性

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
}

給定先前的屬性和 bean,您可以如下取得 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"
    }
}

HttpServletRequestHttpServletResponse 都是選用屬性。如果未提供,它們預設為使用 RequestContextHolder.getRequestAttributes()ServletRequestAttributes

資源擁有者密碼憑證

關於資源擁有者密碼憑證許可的更多詳細資訊,請參閱 OAuth 2.0 授權框架。

請求存取令牌

關於資源擁有者密碼憑證許可的存取令牌請求/回應協定流程,請參閱 OAuth 2.0 授權框架。

資源擁有者密碼憑證許可的 OAuth2AccessTokenResponseClient 的預設實作是 DefaultPasswordTokenResponseClient,它在授權伺服器的令牌端點請求存取令牌時使用 RestOperations

DefaultPasswordTokenResponseClient 很靈活,因為它允許您自訂令牌請求的預先處理或令牌回應的後續處理。

自訂存取令牌請求

如果您需要自訂令牌請求的預先處理,您可以為 DefaultPasswordTokenResponseClient.setRequestEntityConverter() 提供自訂的 Converter<OAuth2PasswordGrantRequest, RequestEntity<?>>。預設實作 (OAuth2PasswordGrantRequestEntityConverter) 建構標準OAuth 2.0 存取令牌請求RequestEntity 表示。但是,提供自訂 Converter 將允許您擴展標準令牌請求並新增自訂參數。

若要僅自訂請求的參數,您可以為 OAuth2PasswordGrantRequestEntityConverter.setParametersConverter() 提供自訂的 Converter<OAuth2PasswordGrantRequest, MultiValueMap<String, String>>,以完全覆寫隨請求傳送的參數。這通常比直接建構 RequestEntity 更簡單。

如果您只想新增額外參數,您可以為 OAuth2PasswordGrantRequestEntityConverter.addParametersConverter() 提供自訂的 Converter<OAuth2PasswordGrantRequest, MultiValueMap<String, String>>,它會建構一個聚合 Converter

自訂 Converter 必須傳回 OAuth 2.0 存取令牌請求的有效 RequestEntity 表示,該請求可被目標 OAuth 2.0 提供者理解。

自訂存取令牌回應

另一方面,如果您需要自訂令牌回應的後續處理,您需要為 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 MVC FormHttpMessageConverter 是必要的,因為它在傳送 OAuth 2.0 存取令牌請求時使用。

OAuth2AccessTokenResponseHttpMessageConverter 是 OAuth 2.0 存取令牌回應的 HttpMessageConverter。您可以為 OAuth2AccessTokenResponseHttpMessageConverter.setTokenResponseConverter() 提供自訂的 Converter<Map<String, String>, OAuth2AccessTokenResponse>,用於將 OAuth 2.0 存取令牌回應參數轉換為 OAuth2AccessTokenResponse

OAuth2ErrorResponseErrorHandler 是一個 ResponseErrorHandler,可以處理 OAuth 2.0 錯誤,例如 400 Bad Request。它使用 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 的實作。

使用存取令牌

請考慮以下 OAuth 2.0 用戶端註冊的 Spring Boot 屬性

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

給定先前的屬性和 bean,您可以如下取得 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"
    }
}

HttpServletRequestHttpServletResponse 都是選用屬性。如果未提供,它們預設為使用 RequestContextHolder.getRequestAttributes()ServletRequestAttributes

JWT Bearer

關於JWT Bearer 許可的更多詳細資訊,請參閱 JSON Web Token (JWT) Profile for OAuth 2.0 Client Authentication and Authorization Grants。

請求存取令牌

關於 JWT Bearer 許可的存取令牌請求/回應協定流程,請參閱 JSON Web Token (JWT) Profile for OAuth 2.0 Client Authentication and Authorization Grants。

JWT Bearer 許可的 OAuth2AccessTokenResponseClient 的預設實作是 DefaultJwtBearerTokenResponseClient,它在授權伺服器的令牌端點請求存取令牌時使用 RestOperations

DefaultJwtBearerTokenResponseClient 非常靈活,因為它允許您自訂令牌請求的預先處理和/或令牌回應的後續處理。

自訂存取令牌請求

如果您需要自訂令牌請求的預先處理,您可以為 DefaultJwtBearerTokenResponseClient.setRequestEntityConverter() 提供自訂的 Converter<JwtBearerGrantRequest, RequestEntity<?>>。預設實作 JwtBearerGrantRequestEntityConverter 建構OAuth 2.0 存取令牌請求RequestEntity 表示。但是,提供自訂 Converter 將允許您擴展令牌請求並新增自訂參數。

若要僅自訂請求的參數,您可以為 JwtBearerGrantRequestEntityConverter.setParametersConverter() 提供自訂的 Converter<JwtBearerGrantRequest, MultiValueMap<String, String>>,以完全覆寫隨請求傳送的參數。這通常比直接建構 RequestEntity 更簡單。

如果您只想新增額外參數,您可以為 JwtBearerGrantRequestEntityConverter.addParametersConverter() 提供自訂的 Converter<JwtBearerGrantRequest, MultiValueMap<String, String>>,它會建構一個聚合 Converter

自訂存取令牌回應

另一方面,如果您需要自訂令牌回應的後續處理,您將需要為 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 MVC FormHttpMessageConverter 是必要的,因為它在傳送 OAuth 2.0 存取令牌請求時使用。

OAuth2AccessTokenResponseHttpMessageConverter 是 OAuth 2.0 存取令牌回應的 HttpMessageConverter。您可以為 OAuth2AccessTokenResponseHttpMessageConverter.setAccessTokenResponseConverter() 提供自訂的 Converter<Map<String, Object>, OAuth2AccessTokenResponse>,用於將 OAuth 2.0 存取令牌回應參數轉換為 OAuth2AccessTokenResponse

OAuth2ErrorResponseErrorHandler 是一個 ResponseErrorHandler,可以處理 OAuth 2.0 錯誤,例如 400 Bad Request。它使用 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)

使用存取令牌

給定以下 OAuth 2.0 用戶端註冊的 Spring Boot 屬性

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 會透過 OAuth2AuthorizationContext.getPrincipal().getPrincipal() 解析 Jwt 斷言,因此在先前的範例中使用了 JwtAuthenticationToken
如果您需要從不同的來源解析 Jwt 斷言,您可以透過自訂的 Function<OAuth2AuthorizationContext, Jwt> 提供 JwtBearerOAuth2AuthorizedClientProvider.setJwtAssertionResolver()

令牌交換

有關令牌交換授權的更多詳細資訊,請參閱 OAuth 2.0 令牌交換。

請求存取令牌

有關令牌交換授權的協定流程,請參閱 令牌交換請求與回應

用於令牌交換授權的 OAuth2AccessTokenResponseClient 預設實作是 DefaultTokenExchangeTokenResponseClient,它在授權伺服器的令牌端點請求存取令牌時使用 RestOperations

DefaultTokenExchangeTokenResponseClient 相當彈性,因為它允許您自訂令牌請求的預先處理和/或令牌回應的後續處理。

自訂存取令牌請求

如果您需要自訂令牌請求的預先處理,您可以透過自訂的 Converter<TokenExchangeGrantRequest, RequestEntity<?>> 提供 DefaultTokenExchangeTokenResponseClient.setRequestEntityConverter()。預設實作 TokenExchangeGrantRequestEntityConverter 會建構 OAuth 2.0 存取令牌請求RequestEntity 表示法。然而,提供自訂的 Converter 將允許您擴展令牌請求並新增自訂參數。

若要僅自訂請求的參數,您可以透過自訂的 Converter<TokenExchangeGrantRequest, MultiValueMap<String, String>> 提供 TokenExchangeGrantRequestEntityConverter.setParametersConverter(),以完全覆寫隨請求傳送的參數。這通常比直接建構 RequestEntity 更簡單。

如果您只想新增額外參數,您可以透過自訂的 Converter<TokenExchangeGrantRequest, MultiValueMap<String, String>> 提供 TokenExchangeGrantRequestEntityConverter.addParametersConverter(),它會建構一個聚合 Converter

自訂存取令牌回應

另一方面,如果您需要自訂令牌回應的後續處理,您需要透過自訂配置的 RestOperations 提供 DefaultTokenExchangeTokenResponseClient.setRestOperations()。預設的 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 MVC FormHttpMessageConverter 是必要的,因為它在傳送 OAuth 2.0 存取令牌請求時使用。

OAuth2AccessTokenResponseHttpMessageConverter 是 OAuth 2.0 存取令牌回應的 HttpMessageConverter。您可以為 OAuth2AccessTokenResponseHttpMessageConverter.setAccessTokenResponseConverter() 提供自訂的 Converter<Map<String, Object>, OAuth2AccessTokenResponse>,用於將 OAuth 2.0 存取令牌回應參數轉換為 OAuth2AccessTokenResponse

OAuth2ErrorResponseErrorHandler 是一個 ResponseErrorHandler,可以處理 OAuth 2.0 錯誤,例如 400 Bad Request。它使用 OAuth2ErrorHttpMessageConverter 將 OAuth 2.0 錯誤參數轉換為 OAuth2Error

無論您是自訂 DefaultTokenExchangeTokenResponseClient 還是提供您自己的 OAuth2AccessTokenResponseClient 實作,您都需要依照以下範例所示進行配置

  • Java

  • Kotlin

// Customize
OAuth2AccessTokenResponseClient<TokenExchangeGrantRequest> tokenExchangeTokenResponseClient = ...

TokenExchangeOAuth2AuthorizedClientProvider tokenExchangeAuthorizedClientProvider = new TokenExchangeOAuth2AuthorizedClientProvider();
tokenExchangeAuthorizedClientProvider.setAccessTokenResponseClient(tokenExchangeTokenResponseClient);

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

...

authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
// Customize
val tokenExchangeTokenResponseClient: OAuth2AccessTokenResponseClient<TokenExchangeGrantRequest> = ...

val tokenExchangeAuthorizedClientProvider = TokenExchangeOAuth2AuthorizedClientProvider()
tokenExchangeAuthorizedClientProvider.setAccessTokenResponseClient(tokenExchangeTokenResponseClient)

val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
        .provider(tokenExchangeAuthorizedClientProvider)
        .build()

...

authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)

使用存取令牌

給定以下 OAuth 2.0 用戶端註冊的 Spring Boot 屬性

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:token-exchange
            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) {

	TokenExchangeOAuth2AuthorizedClientProvider tokenExchangeAuthorizedClientProvider =
			new TokenExchangeOAuth2AuthorizedClientProvider();

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

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

	return authorizedClientManager;
}
@Bean
fun authorizedClientManager(
        clientRegistrationRepository: ClientRegistrationRepository,
        authorizedClientRepository: OAuth2AuthorizedClientRepository): OAuth2AuthorizedClientManager {
    val tokenExchangeAuthorizedClientProvider = TokenExchangeOAuth2AuthorizedClientProvider()
    val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
            .provider(tokenExchangeAuthorizedClientProvider)
            .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

        ...

    }
}
預設情況下,TokenExchangeOAuth2AuthorizedClientProvider 會透過 OAuth2AuthorizationContext.getPrincipal().getPrincipal() 解析主體令牌(作為 OAuth2Token),因此在先前的範例中使用了 JwtAuthenticationToken。預設不會解析行為者令牌。
如果您需要從不同的來源解析主體令牌,您可以透過自訂的 Function<OAuth2AuthorizationContext, OAuth2Token> 提供 TokenExchangeOAuth2AuthorizedClientProvider.setSubjectTokenResolver()
如果您需要解析行為者令牌,您可以透過自訂的 Function<OAuth2AuthorizationContext, OAuth2Token> 提供 TokenExchangeOAuth2AuthorizedClientProvider.setActorTokenResolver()