Spring Boot 不用第三方,照樣玩轉(zhuǎn) OAuth2
在保障API和應(yīng)用程序安全的領(lǐng)域,OAuth2框架應(yīng)用廣泛。不少開發(fā)者借助谷歌(Google)、GitHub、Okta等外部提供商實現(xiàn)相關(guān)功能。不過,若想完全自主掌控身份驗證流程,規(guī)避對第三方服務(wù)的依賴,該如何操作呢?
這時,在Spring Boot應(yīng)用程序中搭建屬于自己的OAuth2服務(wù)器,優(yōu)勢就凸顯出來了:
- 安全隱私升級:數(shù)據(jù)全程在自有系統(tǒng)內(nèi)流轉(zhuǎn),無需擔憂外流風險。
- 靈活定制隨心:能依據(jù)自身需求,定制身份驗證和授權(quán)規(guī)則,適配多樣化業(yè)務(wù)場景。
- 掌控管理自如:可直接對用戶信息、令牌以及安全策略進行管理,操作便捷且高效。
本文為讀者詳細梳理了使用Spring Boot搭建自定義OAuth2服務(wù)器的步驟,助力讀者輕松上手。
一、搭建Spring Boot項目
首先,使用Spring Initializr創(chuàng)建Spring Boot項目,并添加以下依賴項:
- Spring Web
- Spring Security
- OAuth2授權(quán)服務(wù)器
- OAuth2資源服務(wù)器
- 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>
二、配置授權(quán)服務(wù)器
授權(quán)服務(wù)器負責頒發(fā)令牌。我們可以使用Spring Security的內(nèi)置支持對其進行配置。
@Configuration
public class AuthorizationServerConfig {
@Bean
public SecurityFilterChain authorizationSecurityFilterChain(HttpSecurity http) throws Exception {
OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
return http.formLogin().and().build();
}
}
此配置為OAuth2授權(quán)設(shè)置了默認的安全設(shè)置。
三、定義OAuth2客戶端
為了讓應(yīng)用程序能夠請求OAuth2令牌,我們需要定義已注冊的客戶端:
@Configuration
publicclass ClientConfig {
@Bean
public RegisteredClientRepository registeredClientRepository() {
RegisteredClient client = RegisteredClient.withId(UUID.randomUUID().toString())
.clientId("custom-client")
.clientSecret("{noop}secret") // 在生產(chǎn)環(huán)境中請安全存儲!
.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
一旦我們的服務(wù)器頒發(fā)了令牌,就需要通過實施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流程
現(xiàn)在,我們來測試OAuth2的設(shè)置是否正確。
1.啟動授權(quán)服務(wù)器:運行Spring Boot應(yīng)用程序。授權(quán)服務(wù)器將在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'
如果一切設(shè)置正確,你應(yīng)該會看到:
{"message": "This is a secure endpoint accessible with a valid OAuth2 token."}
結(jié)語
通過在Spring Boot中實現(xiàn)自定義的OAuth2授權(quán)服務(wù)器,可以完全掌控用戶身份驗證和安全性。這種方法確保不涉及第三方提供商,從而提供更高的隱私性、靈活性和定制性。