核心介面和類
本節介紹 Spring Security 提供的 OAuth2 核心介面和類。
ClientRegistration
ClientRegistration 是在 OAuth 2.0 或 OpenID Connect 1.0 Provider 中註冊的客戶端的表示。
ClientRegistration 物件包含客戶端 ID、客戶端金鑰、授權授予型別、重定向 URI、範圍、授權 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)
}
}
public static final class ClientSettings {
private boolean requireProofKey; (17)
}
}
| 1 | registrationId:唯一標識 ClientRegistration 的 ID。 |
| 2 | clientId:客戶端識別符號。 |
| 3 | clientSecret:客戶端金鑰。 |
| 4 | clientAuthenticationMethod:用於向 Provider 驗證客戶端的方法。支援的值為 client_secret_basic、client_secret_post、private_key_jwt、client_secret_jwt 和 none (公共客戶端)。 |
| 5 | authorizationGrantType:OAuth 2.0 授權框架定義了四種 授權授予 型別。支援的值為 authorization_code、client_credentials 以及擴充套件授予型別 urn:ietf:params:oauth:grant-type:jwt-bearer。 |
| 6 | redirectUri:授權伺服器在終端使用者透過身份驗證並授權客戶端訪問後,將終端使用者的使用者代理重定向到的客戶端註冊重定向 URI。 |
| 7 | scopes:客戶端在授權請求流期間請求的範圍,例如 openid、email 或 profile。 |
| 8 | clientName:用於客戶端的描述性名稱。該名稱可在某些場景中使用,例如在自動生成的登入頁面中顯示客戶端名稱。 |
| 9 | authorizationUri:授權伺服器的授權端點 URI。 |
| 10 | tokenUri:授權伺服器的令牌端點 URI。 |
| 11 | jwkSetUri:用於從授權伺服器檢索 JSON Web Key (JWK) 集的 URI,其中包含用於驗證 ID 令牌和(可選)UserInfo 響應的 JSON Web Signature (JWS) 的加密金鑰。 |
| 12 | issuerUri:返回 OpenID Connect 1.0 提供商或 OAuth 2.0 授權伺服器的頒發者識別符號 URI。 |
| 13 | configurationMetadata:OpenID Provider 配置資訊。此資訊僅在配置了 Spring Boot 屬性 spring.security.oauth2.client.provider.[providerId].issuerUri 時可用。 |
| 14 | (userInfoEndpoint)uri:用於訪問經過身份驗證的終端使用者宣告和屬性的 UserInfo 端點 URI。 |
| 15 | (userInfoEndpoint)authenticationMethod:向 UserInfo 端點發送訪問令牌時使用的身份驗證方法。支援的值為 header、form 和 query。 |
| 16 | userNameAttributeName:UserInfo 響應中返回的屬性名稱,該屬性引用終端使用者的名稱或識別符號。 |
| 17 | requireProofKey:如果為 true 或 clientAuthenticationMethod 為 none,則將啟用 PKCE。 |
ClientRegistrations 提供了配置 ClientRegistration 的便捷方法,如下所示:
-
Java
-
Kotlin
ClientRegistration clientRegistration =
ClientRegistrations.fromIssuerLocation("https://idp.example.com/issuer").build();
val clientRegistration = ClientRegistrations.fromIssuerLocation("https://idp.example.com/issuer").build()
前面的程式碼依次查詢 idp.example.com/issuer/.well-known/openid-configuration、idp.example.com/.well-known/openid-configuration/issuer 和 idp.example.com/.well-known/oauth-authorization-server/issuer,並在第一個返回 200 響應時停止。
作為替代方案,您可以使用 ClientRegistrations.fromOidcIssuerLocation() 僅查詢 OpenID Connect 提供商的配置端點。
ClientRegistrationRepository
ClientRegistrationRepository 作為 OAuth 2.0 / OpenID Connect 1.0 ClientRegistration 的儲存庫。
|
客戶端註冊資訊最終由關聯的授權伺服器儲存和擁有。此儲存庫提供了檢索主要客戶端註冊資訊子集的功能,這些資訊儲存在授權伺服器中。 |
Spring Boot 自動配置將 spring.security.oauth2.client.registration.[registrationId] 下的每個屬性繫結到 ClientRegistration 的例項,然後將每個 ClientRegistration 例項組合到 ClientRegistrationRepository 中。
|
|
自動配置還將 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。
從開發人員的角度來看,OAuth2AuthorizedClientRepository 或 OAuth2AuthorizedClientService 提供了查詢與客戶端關聯的 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 自動配置在 |
OAuth2AuthorizedClientService 的預設實現是 InMemoryOAuth2AuthorizedClientService,它將 OAuth2AuthorizedClient 物件儲存在記憶體中。
或者,您可以配置 JDBC 實現 JdbcOAuth2AuthorizedClientService 以將 OAuth2AuthorizedClient 例項持久化到資料庫中。
|
|
OAuth2AuthorizedClientManager 和 OAuth2AuthorizedClientProvider
OAuth2AuthorizedClientManager 負責 OAuth2AuthorizedClient 的整體管理。
主要職責包括:
-
使用
OAuth2AuthorizedClientProvider授權(或重新授權)OAuth 2.0 客戶端。 -
委託
OAuth2AuthorizedClient的持久化,通常透過使用OAuth2AuthorizedClientService或OAuth2AuthorizedClientRepository。 -
當 OAuth 2.0 客戶端成功授權(或重新授權)時,委託給
OAuth2AuthorizationSuccessHandler。 -
當 OAuth 2.0 客戶端授權(或重新授權)失敗時,委託給
OAuth2AuthorizationFailureHandler。
OAuth2AuthorizedClientProvider 實現了一種授權(或重新授權)OAuth 2.0 客戶端的策略。實現通常實現授權授予型別,例如 authorization_code、client_credentials 等。
OAuth2AuthorizedClientManager 的預設實現是 DefaultOAuth2AuthorizedClientManager,它與一個 OAuth2AuthorizedClientProvider 相關聯,該提供者可能使用基於委託的組合支援多種授權授予型別。您可以使用 OAuth2AuthorizedClientProviderBuilder 配置和構建基於委託的組合。
以下程式碼顯示瞭如何配置和構建一個 OAuth2AuthorizedClientProvider 組合的示例,該組合支援 authorization_code、refresh_token 和 client_credentials 授權授予型別:
-
Java
-
Kotlin
@Bean
public OAuth2AuthorizedClientManager authorizedClientManager(
ClientRegistrationRepository clientRegistrationRepository,
OAuth2AuthorizedClientRepository authorizedClientRepository) {
OAuth2AuthorizedClientProvider authorizedClientProvider =
OAuth2AuthorizedClientProviderBuilder.builder()
.authorizationCode()
.refreshToken()
.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()
.authorizationCode()
.refreshToken()
.clientCredentials()
.build()
val authorizedClientManager = DefaultOAuth2AuthorizedClientManager(
clientRegistrationRepository, authorizedClientRepository)
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
return authorizedClientManager
}
當授權嘗試成功時,DefaultOAuth2AuthorizedClientManager 委託給 OAuth2AuthorizationSuccessHandler,後者(預設情況下)透過 OAuth2AuthorizedClientRepository 儲存 OAuth2AuthorizedClient。在重新授權失敗的情況下(例如,重新整理令牌不再有效),以前儲存的 OAuth2AuthorizedClient 會透過 RemoveAuthorizedClientOAuth2AuthorizationFailureHandler 從 OAuth2AuthorizedClientRepository 中移除。您可以透過 setAuthorizationSuccessHandler(OAuth2AuthorizationSuccessHandler) 和 setAuthorizationFailureHandler(OAuth2AuthorizationFailureHandler) 自定義預設行為。
DefaultOAuth2AuthorizedClientManager 還關聯了一個型別為 Function<OAuth2AuthorizeRequest, Map<String, Object>> 的 contextAttributesMapper,它負責將 OAuth2AuthorizeRequest 中的屬性對映到與 OAuth2AuthorizationContext 關聯的屬性 Map。當您需要向 OAuth2AuthorizedClientProvider 提供所需(支援的)屬性時,這會很有用。
以下程式碼顯示了 contextAttributesMapper 的示例:
-
Java
-
Kotlin
@Bean
public OAuth2AuthorizedClientManager authorizedClientManager(
ClientRegistrationRepository clientRegistrationRepository,
OAuth2AuthorizedClientRepository authorizedClientRepository) {
OAuth2AuthorizedClientProvider authorizedClientProvider =
OAuth2AuthorizedClientProviderBuilder.builder()
.authorizationCode()
.refreshToken()
.build();
DefaultOAuth2AuthorizedClientManager authorizedClientManager =
new DefaultOAuth2AuthorizedClientManager(
clientRegistrationRepository, authorizedClientRepository);
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
// Assuming the attributes 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 param1 = servletRequest.getParameter("param1");
String param2 = servletRequest.getParameter("param2");
if (StringUtils.hasText(param1) && StringUtils.hasText(param2)) {
contextAttributes = new HashMap<>();
contextAttributes.put("param1", param1);
contextAttributes.put("param2", param2);
}
return contextAttributes;
};
}
@Bean
fun authorizedClientManager(
clientRegistrationRepository: ClientRegistrationRepository,
authorizedClientRepository: OAuth2AuthorizedClientRepository): OAuth2AuthorizedClientManager {
val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
.authorizationCode()
.refreshToken()
.build()
val authorizedClientManager = DefaultOAuth2AuthorizedClientManager(
clientRegistrationRepository, authorizedClientRepository)
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
// Assuming the attributes 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 param1: String = servletRequest.getParameter("param1")
val param2: String = servletRequest.getParameter("param2")
if (StringUtils.hasText(param1) && StringUtils.hasText(param2)) {
contextAttributes = hashMapOf()
contextAttributes["param1"] = param1
contextAttributes["param2"] = param2
}
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
}