Spring Boot 不用第三方,照樣玩轉 OAuth2
在保障API和應用程序安全的領域,OAuth2框架應用廣泛。不少開發者借助谷歌(Google)、GitHub、Okta等外部提供商實現相關功能。不過,若想完全自主掌控身份驗證流程,規避對第三方服務的依賴,該如何操作呢?
這時,在Spring Boot應用程序中搭建屬于自己的OAuth2服務器,優勢就凸顯出來了:
- 安全隱私升級:數據全程在自有系統內流轉,無需擔憂外流風險。
- 靈活定制隨心:能依據自身需求,定制身份驗證和授權規則,適配多樣化業務場景。
- 掌控管理自如:可直接對用戶信息、令牌以及安全策略進行管理,操作便捷且高效。
本文為讀者詳細梳理了使用Spring Boot搭建自定義OAuth2服務器的步驟,助力讀者輕松上手。
一、搭建Spring Boot項目
首先,使用Spring Initializr創建Spring Boot項目,并添加以下依賴項:
- Spring Web
- Spring Security
- OAuth2授權服務器
- OAuth2資源服務器
- Spring Data JPA(用于用戶存儲)
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-authorization-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
二、配置授權服務器
授權服務器負責頒發令牌。我們可以使用Spring Security的內置支持對其進行配置。
@Configuration
public class AuthorizationServerConfig {
@Bean
public SecurityFilterChain authorizationSecurityFilterChain(HttpSecurity http) throws Exception {
OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
return http.formLogin().and().build();
}
}
此配置為OAuth2授權設置了默認的安全設置。
三、定義OAuth2客戶端
為了讓應用程序能夠請求OAuth2令牌,我們需要定義已注冊的客戶端:
@Configuration
publicclass ClientConfig {
@Bean
public RegisteredClientRepository registeredClientRepository() {
RegisteredClient client = RegisteredClient.withId(UUID.randomUUID().toString())
.clientId("custom-client")
.clientSecret("{noop}secret") // 在生產環境中請安全存儲!
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN)
.redirectUri("http://localhost:8081/login/oauth2/code/custom-client")
.scope(OidcScopes.OPENID)
.build();
returnnew InMemoryRegisteredClientRepository(client);
}
}
這定義了一個使用客戶端憑證進行身份驗證、可以請求令牌的客戶端。
四、使用OAuth2令牌保護API
一旦我們的服務器頒發了令牌,就需要通過實施OAuth2身份驗證來保護API。
@RestController
@RequestMapping("/api")
public class SecureController {
@GetMapping("/secure")
public String secureEndpoint() {
return "This is a secure endpoint accessible with a valid OAuth2 token.";
}
}
五、測試OAuth2流程
現在,我們來測試OAuth2的設置是否正確。
1.啟動授權服務器:運行Spring Boot應用程序。授權服務器將在http://localhost:9000
可用。
2.請求OAuth2令牌:使用curl
命令請求令牌:
curl --location --request POST 'http://localhost:9000/oauth2/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'grant_type=client_credentials' \
--data-urlencode 'client_id=custom-client' \
--data-urlencode 'client_secret=secret'
3.使用令牌訪問安全API:獲取令牌后,使用它來訪問安全API:
curl --location --request GET 'http://localhost:8080/api/secure' \
--header 'Authorization: Bearer YOUR_ACCESS_TOKEN'
如果一切設置正確,你應該會看到:
{"message": "This is a secure endpoint accessible with a valid OAuth2 token."}
結語
通過在Spring Boot中實現自定義的OAuth2授權服務器,可以完全掌控用戶身份驗證和安全性。這種方法確保不涉及第三方提供商,從而提供更高的隱私性、靈活性和定制性。