核心介面與類別

本節描述 Spring Security 提供的 OAuth2 核心介面與類別。

ClientRegistration

ClientRegistration 代表在 OAuth 2.0 或 OpenID Connect 1.0 提供者註冊的用戶端。

ClientRegistration 物件包含資訊,例如用戶端 ID、用戶端密碼、授權類型、重新導向 URI、Scope、授權 URI、權杖 URI 和其他詳細資訊。

ClientRegistration 及其屬性定義如下

public final class ClientRegistration {
	private String registrationId;	(1)
	private String clientId;	(2)
	private String clientSecret;	(3)
	private ClientAuthenticationMethod clientAuthenticationMethod;	(4)
	private AuthorizationGrantType authorizationGrantType;	(5)
	private String redirectUri;	(6)
	private Set<String> scopes;	(7)
	private ProviderDetails providerDetails;
	private String clientName;	(8)

	public class ProviderDetails {
		private String authorizationUri;	(9)
		private String tokenUri;	(10)
		private UserInfoEndpoint userInfoEndpoint;
		private String jwkSetUri;	(11)
		private String issuerUri;	(12)
        private Map<String, Object> configurationMetadata;  (13)

		public class UserInfoEndpoint {
			private String uri;	(14)
            private AuthenticationMethod authenticationMethod;  (15)
			private String userNameAttributeName;	(16)

		}
	}
}
1 registrationId:唯一識別 ClientRegistration 的 ID。
2 clientId:用戶端識別碼。
3 clientSecret:用戶端密碼。
4 clientAuthenticationMethod:用於驗證用戶端與提供者之間身份的方法。支援的值為 client_secret_basicclient_secret_postprivate_key_jwtclient_secret_jwtnone (公開用戶端)
5 authorizationGrantType:OAuth 2.0 授權框架定義了四種 授權類型。支援的值為 authorization_codeclient_credentialspassword,以及擴充授權類型 urn:ietf:params:oauth:grant-type:jwt-bearer
6 redirectUri:用戶端註冊的重新導向 URI,授權伺服器 在終端使用者驗證身份並授權用戶端存取後,將終端使用者的使用者代理程式重新導向至此 URI。
7 scopes:用戶端在授權請求流程中請求的 Scope,例如 openid、email 或 profile。
8 clientName:用於用戶端的描述性名稱。此名稱可能用於某些情境,例如在自動產生的登入頁面中顯示用戶端的名稱時。
9 authorizationUri:授權伺服器的授權端點 URI。
10 tokenUri:授權伺服器的權杖端點 URI。
11 jwkSetUri:用於從授權伺服器檢索 JSON Web Key (JWK) Set 的 URI,其中包含用於驗證 ID 權杖的 JSON Web Signature (JWS) 和(可選)UserInfo 回應的加密金鑰。
12 issuerUri:傳回 OpenID Connect 1.0 提供者或 OAuth 2.0 授權伺服器的發行者識別符 URI。
13 configurationMetadataOpenID 提供者組態資訊。只有在設定 Spring Boot 屬性 spring.security.oauth2.client.provider.[providerId].issuerUri 時,此資訊才可用。
14 (userInfoEndpoint)uri:UserInfo 端點 URI,用於存取已驗證終端使用者的宣告和屬性。
15 (userInfoEndpoint)authenticationMethod:將存取權杖傳送至 UserInfo 端點時使用的身份驗證方法。支援的值為 headerformquery
16 userNameAttributeName:在 UserInfo 回應中傳回的屬性名稱,該屬性引用終端使用者的名稱或識別符。

您可以透過探索 OpenID Connect 提供者的 組態端點 或授權伺服器的 Metadata 端點,初步設定 ClientRegistration

ClientRegistrations 提供方便的方法,以這種方式組態 ClientRegistration,如下所示

  • Java

  • Kotlin

ClientRegistration clientRegistration =
    ClientRegistrations.fromIssuerLocation("https://idp.example.com/issuer").build();
val clientRegistration = ClientRegistrations.fromIssuerLocation("https://idp.example.com/issuer").build()

作為替代方案,您可以使用 ClientRegistrations.fromOidcIssuerLocation() 僅查詢 OpenID Connect 提供者的組態端點。

ClientRegistrationRepository

ClientRegistrationRepository 作為 OAuth 2.0 / OpenID Connect 1.0 ClientRegistration 的儲存庫。

用戶端註冊資訊最終由相關的授權伺服器儲存和擁有。此儲存庫提供檢索主要用戶端註冊資訊子集的能力,這些資訊儲存在授權伺服器中。

Spring Boot 自動組態將 spring.security.oauth2.client.registration.[registrationId] 下的每個屬性繫結到 ClientRegistration 的實例,然後在 ClientRegistrationRepository 中組成每個 ClientRegistration 實例。

ClientRegistrationRepository 的預設實作是 InMemoryClientRegistrationRepository

自動組態也會將 ClientRegistrationRepository 註冊為 ApplicationContext 中的 @Bean,以便應用程式在需要時可以進行依賴注入。

以下清單顯示一個範例

  • Java

  • Kotlin

@Controller
public class OAuth2ClientController {

	@Autowired
	private ClientRegistrationRepository clientRegistrationRepository;

	@GetMapping("/")
	public String index() {
		ClientRegistration oktaRegistration =
			this.clientRegistrationRepository.findByRegistrationId("okta");

		...

		return "index";
	}
}
@Controller
class OAuth2ClientController {

    @Autowired
    private lateinit var clientRegistrationRepository: ClientRegistrationRepository

    @GetMapping("/")
    fun index(): String {
        val oktaRegistration =
                this.clientRegistrationRepository.findByRegistrationId("okta")

        //...

        return "index";
    }
}

OAuth2AuthorizedClient

OAuth2AuthorizedClient 代表已授權的用戶端。當終端使用者(資源擁有者)已授權用戶端存取其受保護資源時,用戶端被視為已授權。

OAuth2AuthorizedClient 的用途是將 OAuth2AccessToken(和可選的 OAuth2RefreshToken)與 ClientRegistration(用戶端)和資源擁有者(即授予授權的 Principal 終端使用者)建立關聯。

OAuth2AuthorizedClientRepository 和 OAuth2AuthorizedClientService

OAuth2AuthorizedClientRepository 負責在 Web 請求之間持久化 OAuth2AuthorizedClient,而 OAuth2AuthorizedClientService 的主要角色是在應用程式層級管理 OAuth2AuthorizedClient

從開發人員的角度來看,OAuth2AuthorizedClientRepositoryOAuth2AuthorizedClientService 提供了查找與用戶端關聯的 OAuth2AccessToken 的能力,以便可以用於啟動受保護的資源請求。

以下清單顯示一個範例

  • Java

  • Kotlin

@Controller
public class OAuth2ClientController {

    @Autowired
    private OAuth2AuthorizedClientService authorizedClientService;

    @GetMapping("/")
    public String index(Authentication authentication) {
        OAuth2AuthorizedClient authorizedClient =
            this.authorizedClientService.loadAuthorizedClient("okta", authentication.getName());

        OAuth2AccessToken accessToken = authorizedClient.getAccessToken();

        ...

        return "index";
    }
}
@Controller
class OAuth2ClientController {

    @Autowired
    private lateinit var authorizedClientService: OAuth2AuthorizedClientService

    @GetMapping("/")
    fun index(authentication: Authentication): String {
        val authorizedClient: OAuth2AuthorizedClient =
            this.authorizedClientService.loadAuthorizedClient("okta", authentication.getName());
        val accessToken = authorizedClient.accessToken

        ...

        return "index";
    }
}

Spring Boot 自動組態在 ApplicationContext 中註冊 OAuth2AuthorizedClientRepositoryOAuth2AuthorizedClientService @Bean。但是,應用程式可以覆寫並註冊自訂 OAuth2AuthorizedClientRepositoryOAuth2AuthorizedClientService @Bean

OAuth2AuthorizedClientService 的預設實作是 InMemoryOAuth2AuthorizedClientService,它在記憶體中儲存 OAuth2AuthorizedClient 物件。

或者,您可以組態 JDBC 實作 JdbcOAuth2AuthorizedClientService,以在資料庫中持久化 OAuth2AuthorizedClient 實例。

JdbcOAuth2AuthorizedClientService 依賴於 OAuth 2.0 用戶端結構描述 中描述的表格定義。

OAuth2AuthorizedClientManager 和 OAuth2AuthorizedClientProvider

OAuth2AuthorizedClientManager 負責 OAuth2AuthorizedClient 的整體管理。

主要職責包括

  • 使用 OAuth2AuthorizedClientProvider 授權(或重新授權)OAuth 2.0 用戶端。

  • 委派 OAuth2AuthorizedClient 的持久性,通常使用 OAuth2AuthorizedClientServiceOAuth2AuthorizedClientRepository

  • 當 OAuth 2.0 用戶端已成功授權(或重新授權)時,委派給 OAuth2AuthorizationSuccessHandler

  • 當 OAuth 2.0 用戶端授權(或重新授權)失敗時,委派給 OAuth2AuthorizationFailureHandler

OAuth2AuthorizedClientProvider 實作授權(或重新授權)OAuth 2.0 用戶端的策略。實作通常實作授權類型,例如 authorization_codeclient_credentials 和其他類型。

OAuth2AuthorizedClientManager 的預設實作是 DefaultOAuth2AuthorizedClientManager,它與 OAuth2AuthorizedClientProvider 關聯,後者可以使用基於委派的複合支援多種授權類型。您可以使用 OAuth2AuthorizedClientProviderBuilder 組態和建置基於委派的複合。

以下程式碼顯示如何組態和建置 OAuth2AuthorizedClientProvider 複合的範例,該複合提供對 authorization_coderefresh_tokenclient_credentialspassword 授權類型的支援

  • Java

  • Kotlin

@Bean
public OAuth2AuthorizedClientManager authorizedClientManager(
		ClientRegistrationRepository clientRegistrationRepository,
		OAuth2AuthorizedClientRepository authorizedClientRepository) {

	OAuth2AuthorizedClientProvider authorizedClientProvider =
			OAuth2AuthorizedClientProviderBuilder.builder()
					.authorizationCode()
					.refreshToken()
					.clientCredentials()
					.password()
					.build();

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

	return authorizedClientManager;
}
@Bean
fun authorizedClientManager(
        clientRegistrationRepository: ClientRegistrationRepository,
        authorizedClientRepository: OAuth2AuthorizedClientRepository): OAuth2AuthorizedClientManager {
    val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
            .authorizationCode()
            .refreshToken()
            .clientCredentials()
            .password()
            .build()
    val authorizedClientManager = DefaultOAuth2AuthorizedClientManager(
            clientRegistrationRepository, authorizedClientRepository)
    authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
    return authorizedClientManager
}

當授權嘗試成功時,DefaultOAuth2AuthorizedClientManager 委派給 OAuth2AuthorizationSuccessHandler,後者(預設情況下)透過 OAuth2AuthorizedClientRepository 儲存 OAuth2AuthorizedClient。在重新授權失敗的情況下(例如,重新整理權杖不再有效),先前儲存的 OAuth2AuthorizedClient 會透過 RemoveAuthorizedClientOAuth2AuthorizationFailureHandlerOAuth2AuthorizedClientRepository 中移除。您可以透過 setAuthorizationSuccessHandler(OAuth2AuthorizationSuccessHandler)setAuthorizationFailureHandler(OAuth2AuthorizationFailureHandler) 自訂預設行為。

DefaultOAuth2AuthorizedClientManager 也與 contextAttributesMapper 類型 Function<OAuth2AuthorizeRequest, Map<String, Object>> 關聯,它負責將 OAuth2AuthorizeRequest 中的屬性對應到要與 OAuth2AuthorizationContext 關聯的屬性 Map。當您需要向 OAuth2AuthorizedClientProvider 提供所需的(支援的)屬性時,這可能很有用,例如。 PasswordOAuth2AuthorizedClientProvider 需要資源擁有者的 usernamepasswordOAuth2AuthorizationContext.getAttributes() 中可用。

以下程式碼顯示 contextAttributesMapper 的範例

  • 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: String = servletRequest.getParameter(OAuth2ParameterNames.USERNAME)
        val password: String = 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
    }
}

DefaultOAuth2AuthorizedClientManager 設計為在 HttpServletRequest 的上下文中使用。當在 HttpServletRequest 上下文之外操作時,請改用 AuthorizedClientServiceOAuth2AuthorizedClientManager

服務應用程式是何時使用 AuthorizedClientServiceOAuth2AuthorizedClientManager 的常見用例。服務應用程式通常在後台執行,沒有任何使用者互動,並且通常在系統層級帳戶而不是使用者帳戶下執行。以 client_credentials 授權類型組態的 OAuth 2.0 用戶端可以視為一種服務應用程式。

以下程式碼顯示如何組態 AuthorizedClientServiceOAuth2AuthorizedClientManager 的範例,該複合提供對 client_credentials 授權類型的支援

  • Java

  • Kotlin

@Bean
public OAuth2AuthorizedClientManager authorizedClientManager(
		ClientRegistrationRepository clientRegistrationRepository,
		OAuth2AuthorizedClientService authorizedClientService) {

	OAuth2AuthorizedClientProvider authorizedClientProvider =
			OAuth2AuthorizedClientProviderBuilder.builder()
					.clientCredentials()
					.build();

	AuthorizedClientServiceOAuth2AuthorizedClientManager authorizedClientManager =
			new AuthorizedClientServiceOAuth2AuthorizedClientManager(
					clientRegistrationRepository, authorizedClientService);
	authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);

	return authorizedClientManager;
}
@Bean
fun authorizedClientManager(
        clientRegistrationRepository: ClientRegistrationRepository,
        authorizedClientService: OAuth2AuthorizedClientService): OAuth2AuthorizedClientManager {
    val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
            .clientCredentials()
            .build()
    val authorizedClientManager = AuthorizedClientServiceOAuth2AuthorizedClientManager(
            clientRegistrationRepository, authorizedClientService)
    authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
    return authorizedClientManager
}