核心介面和類
本節介紹 Spring Security 提供的 OAuth2 核心介面和類。
ClientRegistration
ClientRegistration
是在 OAuth 2.0 或 OpenID Connect 1.0 Provider 註冊的客戶端的表示。
ClientRegistration
物件包含客戶端 ID、客戶端 Secret、授權許可型別、重定向 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 :客戶端 Secret。 |
4 | clientAuthenticationMethod :用於向 Provider 認證客戶端的方法。支援的值包括 client_secret_basic、client_secret_post、private_key_jwt、client_secret_jwt 和 none (公共客戶端)。 |
5 | authorizationGrantType :OAuth 2.0 授權框架定義了四種 授權許可(Authorization Grant) 型別。支援的值包括 authorization_code 、client_credentials 、password ,以及擴充套件許可型別 urn:ietf:params:oauth:grant-type:jwt-bearer 。 |
6 | redirectUri :客戶端註冊的重定向 URI,在終端使用者完成認證並授權客戶端訪問後,授權伺服器(Authorization Server) 會將終端使用者的 user-agent 重定向到此 URI。 |
7 | scopes :客戶端在授權請求流程中請求的作用域(scope),例如 openid、email 或 profile。 |
8 | clientName :用於客戶端的描述性名稱。此名稱可在某些場景下使用,例如在自動生成的登入頁面中顯示客戶端名稱。 |
9 | authorizationUri :授權伺服器的授權端點(Authorization Endpoint)URI。 |
10 | tokenUri :授權伺服器的令牌端點(Token Endpoint)URI。 |
11 | jwkSetUri :用於從授權伺服器檢索 JSON Web Key (JWK) Set 的 URI,其中包含用於驗證 ID Token 和(可選地)UserInfo 響應的 JSON Web Signature (JWS) 的加密金鑰。 |
12 | issuerUri :返回 OpenID Connect 1.0 provider 或 OAuth 2.0 授權伺服器的頒發者識別符號 URI。 |
13 | configurationMetadata :OpenID Provider 配置資訊。此資訊僅在配置了 Spring Boot 屬性 spring.security.oauth2.client.provider.[providerId].issuerUri 時可用。 |
14 | (userInfoEndpoint)uri :用於訪問已認證終端使用者的宣告(claims)和屬性的 UserInfo 端點 URI。 |
15 | (userInfoEndpoint)authenticationMethod :將訪問令牌傳送到 UserInfo 端點時使用的認證方法。支援的值包括 header、form 和 query。 |
16 | userNameAttributeName :UserInfo 響應中返回的屬性名稱,該屬性引用終端使用者的名稱或識別符號。 |
您可以使用 OpenID Connect Provider 的配置端點(Configuration endpoint)發現或授權伺服器的元資料端點(Metadata endpoint)發現來初步配置 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()
前面的程式碼按順序查詢 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 Provider 的配置端點。
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
是授權客戶端(Authorized Client)的表示。當終端使用者(資源所有者 Resource Owner)授予客戶端訪問其受保護資源的授權時,該客戶端被認為是授權的(authorized)。
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
配置和構建基於委託的組合。
以下程式碼示例演示瞭如何配置和構建一個支援 authorization_code
、refresh_token
、client_credentials
和 password
授權許可型別的 OAuth2AuthorizedClientProvider
組合:
-
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
將透過 RemoveAuthorizedClientOAuth2AuthorizationFailureHandler
從 OAuth2AuthorizedClientRepository
中移除。您可以透過 setAuthorizationSuccessHandler(OAuth2AuthorizationSuccessHandler)
和 setAuthorizationFailureHandler(OAuth2AuthorizationFailureHandler)
來自定義預設行為。
DefaultOAuth2AuthorizedClientManager
還關聯了一個型別為 Function<OAuth2AuthorizeRequest, Map<String, Object>>
的 contextAttributesMapper
,它負責將屬性從 OAuth2AuthorizeRequest
對映到一個屬性 Map
,以便與 OAuth2AuthorizationContext
關聯。當您需要向 OAuth2AuthorizedClientProvider
提供必需(支援)的屬性時,這會非常有用,例如 PasswordOAuth2AuthorizedClientProvider
要求資源所有者的 username
和 password
在 OAuth2AuthorizationContext.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 客戶端可以被視為一種服務應用程式。
以下程式碼示例演示瞭如何配置支援 client_credentials
許可型別的 AuthorizedClientServiceOAuth2AuthorizedClientManager
:
-
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
}