核心配置
Spring Boot 示例
Spring Boot 為 OAuth 2.0 登入提供了完整的自動配置功能。
本節展示瞭如何使用 Google 作為 身份驗證提供商 (Authentication Provider) 來配置 OAuth 2.0 登入 WebFlux 示例,並涵蓋以下主題:
初始設定
要使用 Google 的 OAuth 2.0 身份驗證系統進行登入,您必須在 Google API 控制檯中設定一個專案以獲取 OAuth 2.0 憑據。
請遵循 OpenID Connect 頁面上的說明,從“設定 OAuth 2.0”部分開始。
完成“獲取 OAuth 2.0 憑據”說明後,您應該擁有一個新的 OAuth 客戶端,其憑據包括客戶端 ID 和客戶端金鑰。
設定重定向 URI
重定向 URI 是應用程式中的路徑,在終端使用者透過 Google 身份驗證並被授予訪問同意頁面上的 OAuth 客戶端(在上一步中建立的)的許可權後,終端使用者的使用者代理將被重定向回該路徑。
在“設定重定向 URI”小節中,確保 授權重定向 URI 欄位設定為 localhost:8080/login/oauth2/code/google。
|
預設的重定向 URI 模板是 |
配置 application.yml
現在您已經擁有一個使用 Google 的新 OAuth 客戶端,您需要配置應用程式以使用該 OAuth 客戶端進行 身份驗證流程。為此:
-
前往
application.yml並設定以下配置:示例 1. OAuth 客戶端屬性spring: security: oauth2: client: registration: (1) google: (2) client-id: google-client-id client-secret: google-client-secret1 spring.security.oauth2.client.registration是 OAuth 客戶端屬性的基本字首。2 基本屬性字首後面是 ClientRegistration的 ID,例如 google。 -
將
client-id和client-secret屬性中的值替換為您之前建立的 OAuth 2.0 憑據。
啟動應用程式
啟動 Spring Boot 示例並訪問 localhost:8080。您將被重定向到預設的 自動生成 的登入頁面,該頁面顯示一個 Google 連結。
單擊 Google 連結,您將被重定向到 Google 進行身份驗證。
使用您的 Google 帳戶憑據進行身份驗證後,下一頁將顯示同意螢幕。同意螢幕要求您允許或拒絕訪問您之前建立的 OAuth 客戶端。單擊 允許 以授權 OAuth 客戶端訪問您的電子郵件地址和基本個人資料資訊。
此時,OAuth 客戶端將從 使用者資訊端點 (UserInfo Endpoint) 檢索您的電子郵件地址和基本個人資料資訊,並建立一個已認證的會話。
Spring Boot 屬性對映
下表概述了 Spring Boot OAuth 客戶端屬性到 ClientRegistration 屬性的對映。
| Spring Boot | ClientRegistration |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
CommonOAuth2Provider
CommonOAuth2Provider 為許多知名提供商(Google、GitHub、Facebook、X 和 Okta)預定義了一組預設客戶端屬性。
例如,提供商的 authorization-uri、token-uri 和 user-info-uri 不經常更改。因此,提供預設值以減少所需配置是合理的。
如前所述,當我們配置 Google 客戶端時,只需要 client-id 和 client-secret 屬性。
以下列表顯示了一個示例
spring:
security:
oauth2:
client:
registration:
google:
client-id: google-client-id
client-secret: google-client-secret
客戶端屬性的自動預設在這裡無縫工作,因為 registrationId (google) 與 CommonOAuth2Provider 中的 GOOGLE enum(不區分大小寫)匹配。 |
在您可能希望指定不同 registrationId 的情況下,例如 google-login,您仍然可以透過配置 provider 屬性來利用客戶端屬性的自動預設。
以下列表顯示了一個示例
spring:
security:
oauth2:
client:
registration:
google-login: (1)
provider: google (2)
client-id: google-client-id
client-secret: google-client-secret
| 1 | registrationId 設定為 google-login。 |
| 2 | provider 屬性設定為 google,這將利用 CommonOAuth2Provider.GOOGLE.getBuilder() 中設定的客戶端屬性的自動預設。 |
配置自定義提供商屬性
有一些 OAuth 2.0 提供商支援多租戶,這導致每個租戶(或子域)都有不同的協議端點。
例如,在 Okta 中註冊的 OAuth 客戶端被分配到一個特定的子域,並擁有自己的協議端點。
對於這些情況,Spring Boot 提供了以下基本屬性來配置自定義提供商屬性:spring.security.oauth2.client.provider.[providerId]。
以下列表顯示了一個示例
spring:
security:
oauth2:
client:
registration:
okta:
client-id: okta-client-id
client-secret: okta-client-secret
provider:
okta: (1)
authorization-uri: https://your-subdomain.oktapreview.com/oauth2/v1/authorize
token-uri: https://your-subdomain.oktapreview.com/oauth2/v1/token
user-info-uri: https://your-subdomain.oktapreview.com/oauth2/v1/userinfo
user-name-attribute: sub
jwk-set-uri: https://your-subdomain.oktapreview.com/oauth2/v1/keys
| 1 | 基本屬性 (spring.security.oauth2.client.provider.okta) 允許自定義配置協議端點位置。 |
覆蓋 Spring Boot 自動配置
Spring Boot OAuth 客戶端支援的自動配置類是 ReactiveOAuth2ClientAutoConfiguration。
它執行以下任務:
-
註冊一個由配置的 OAuth 客戶端屬性組成的
ClientRegistration(s) 的ReactiveClientRegistrationRepository@Bean。 -
註冊一個
SecurityWebFilterChain@Bean並透過serverHttpSecurity.oauth2Login()啟用 OAuth 2.0 登入。
如果您需要根據您的具體要求覆蓋自動配置,您可以透過以下方式進行:
註冊一個 ReactiveClientRegistrationRepository @Bean
以下示例展示瞭如何註冊一個 ReactiveClientRegistrationRepository @Bean:
-
Java
-
Kotlin
@Configuration
public class OAuth2LoginConfig {
@Bean
public ReactiveClientRegistrationRepository clientRegistrationRepository() {
return new InMemoryReactiveClientRegistrationRepository(this.googleClientRegistration());
}
private ClientRegistration googleClientRegistration() {
return ClientRegistration.withRegistrationId("google")
.clientId("google-client-id")
.clientSecret("google-client-secret")
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.redirectUri("{baseUrl}/login/oauth2/code/{registrationId}")
.scope("openid", "profile", "email", "address", "phone")
.authorizationUri("https://#/o/oauth2/v2/auth")
.tokenUri("https://www.googleapis.com/oauth2/v4/token")
.userInfoUri("https://www.googleapis.com/oauth2/v3/userinfo")
.userNameAttributeName(IdTokenClaimNames.SUB)
.jwkSetUri("https://www.googleapis.com/oauth2/v3/certs")
.clientName("Google")
.build();
}
}
@Configuration
class OAuth2LoginConfig {
@Bean
fun clientRegistrationRepository(): ReactiveClientRegistrationRepository {
return InMemoryReactiveClientRegistrationRepository(googleClientRegistration())
}
private fun googleClientRegistration(): ClientRegistration {
return ClientRegistration.withRegistrationId("google")
.clientId("google-client-id")
.clientSecret("google-client-secret")
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.redirectUri("{baseUrl}/login/oauth2/code/{registrationId}")
.scope("openid", "profile", "email", "address", "phone")
.authorizationUri("https://#/o/oauth2/v2/auth")
.tokenUri("https://www.googleapis.com/oauth2/v4/token")
.userInfoUri("https://www.googleapis.com/oauth2/v3/userinfo")
.userNameAttributeName(IdTokenClaimNames.SUB)
.jwkSetUri("https://www.googleapis.com/oauth2/v3/certs")
.clientName("Google")
.build()
}
}
註冊一個 SecurityWebFilterChain @Bean
以下示例展示瞭如何使用 @EnableWebFluxSecurity 註冊一個 SecurityWebFilterChain @Bean,並透過 serverHttpSecurity.oauth2Login() 啟用 OAuth 2.0 登入:
-
Java
-
Kotlin
@Configuration
@EnableWebFluxSecurity
public class OAuth2LoginSecurityConfig {
@Bean
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
http
.authorizeExchange((authorize) -> authorize
.anyExchange().authenticated()
)
.oauth2Login(withDefaults());
return http.build();
}
}
@Configuration
@EnableWebFluxSecurity
class OAuth2LoginSecurityConfig {
@Bean
fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
http {
authorizeExchange {
authorize(anyExchange, authenticated)
}
oauth2Login { }
}
return http.build()
}
}
完全覆蓋自動配置
以下示例展示瞭如何透過註冊一個 ReactiveClientRegistrationRepository @Bean 和一個 SecurityWebFilterChain @Bean 來完全覆蓋自動配置。
-
Java
-
Kotlin
@Configuration
@EnableWebFluxSecurity
public class OAuth2LoginConfig {
@Bean
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
http
.authorizeExchange((authorize) -> authorize
.anyExchange().authenticated()
)
.oauth2Login(withDefaults());
return http.build();
}
@Bean
public ReactiveClientRegistrationRepository clientRegistrationRepository() {
return new InMemoryReactiveClientRegistrationRepository(this.googleClientRegistration());
}
private ClientRegistration googleClientRegistration() {
return ClientRegistration.withRegistrationId("google")
.clientId("google-client-id")
.clientSecret("google-client-secret")
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.redirectUri("{baseUrl}/login/oauth2/code/{registrationId}")
.scope("openid", "profile", "email", "address", "phone")
.authorizationUri("https://#/o/oauth2/v2/auth")
.tokenUri("https://www.googleapis.com/oauth2/v4/token")
.userInfoUri("https://www.googleapis.com/oauth2/v3/userinfo")
.userNameAttributeName(IdTokenClaimNames.SUB)
.jwkSetUri("https://www.googleapis.com/oauth2/v3/certs")
.clientName("Google")
.build();
}
}
@Configuration
@EnableWebFluxSecurity
class OAuth2LoginConfig {
@Bean
fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
http {
authorizeExchange {
authorize(anyExchange, authenticated)
}
oauth2Login { }
}
return http.build()
}
@Bean
fun clientRegistrationRepository(): ReactiveClientRegistrationRepository {
return InMemoryReactiveClientRegistrationRepository(googleClientRegistration())
}
private fun googleClientRegistration(): ClientRegistration {
return ClientRegistration.withRegistrationId("google")
.clientId("google-client-id")
.clientSecret("google-client-secret")
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.redirectUri("{baseUrl}/login/oauth2/code/{registrationId}")
.scope("openid", "profile", "email", "address", "phone")
.authorizationUri("https://#/o/oauth2/v2/auth")
.tokenUri("https://www.googleapis.com/oauth2/v4/token")
.userInfoUri("https://www.googleapis.com/oauth2/v3/userinfo")
.userNameAttributeName(IdTokenClaimNames.SUB)
.jwkSetUri("https://www.googleapis.com/oauth2/v3/certs")
.clientName("Google")
.build()
}
}
不使用 Spring Boot 的 Java 配置
如果您無法使用 Spring Boot 並希望配置 CommonOAuth2Provider 中預定義的一個提供商(例如 Google),請應用以下配置:
-
Java
-
Kotlin
@Configuration
@EnableWebFluxSecurity
public class OAuth2LoginConfig {
@Bean
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
http
.authorizeExchange((authorize) -> authorize
.anyExchange().authenticated()
)
.oauth2Login(withDefaults());
return http.build();
}
@Bean
public ReactiveClientRegistrationRepository clientRegistrationRepository() {
return new InMemoryReactiveClientRegistrationRepository(this.googleClientRegistration());
}
@Bean
public ReactiveOAuth2AuthorizedClientService authorizedClientService(
ReactiveClientRegistrationRepository clientRegistrationRepository) {
return new InMemoryReactiveOAuth2AuthorizedClientService(clientRegistrationRepository);
}
@Bean
public ServerOAuth2AuthorizedClientRepository authorizedClientRepository(
ReactiveOAuth2AuthorizedClientService authorizedClientService) {
return new AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository(authorizedClientService);
}
private ClientRegistration googleClientRegistration() {
return CommonOAuth2Provider.GOOGLE.getBuilder("google")
.clientId("google-client-id")
.clientSecret("google-client-secret")
.build();
}
}
@Configuration
@EnableWebFluxSecurity
class OAuth2LoginConfig {
@Bean
fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
http {
authorizeExchange {
authorize(anyExchange, authenticated)
}
oauth2Login { }
}
return http.build()
}
@Bean
fun clientRegistrationRepository(): ReactiveClientRegistrationRepository {
return InMemoryReactiveClientRegistrationRepository(googleClientRegistration())
}
@Bean
fun authorizedClientService(
clientRegistrationRepository: ReactiveClientRegistrationRepository
): ReactiveOAuth2AuthorizedClientService {
return InMemoryReactiveOAuth2AuthorizedClientService(clientRegistrationRepository)
}
@Bean
fun authorizedClientRepository(
authorizedClientService: ReactiveOAuth2AuthorizedClientService
): ServerOAuth2AuthorizedClientRepository {
return AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository(authorizedClientService)
}
private fun googleClientRegistration(): ClientRegistration {
return CommonOAuth2Provider.GOOGLE.getBuilder("google")
.clientId("google-client-id")
.clientSecret("google-client-secret")
.build()
}
}