一、OAuth 2.0 簡介
OAuth是一種Web開放標準協議,允許用戶讓第三方應用訪問其在某一網站上存儲的私密資源,而不需要將用戶名和密碼提供給第三方應用或分享他們的cookie。
OAuth2.0是之前版本的OAuth1.0的更新版。與OAuth1.0相比,OAuth2.0通過之前的授權方式為用戶提供更加簡便的授權方式。它解決了 OAuth1.0 中的某些漏洞,同時在安全和可用性之間達到了平衡。
二、Spring Boot OAuth2.0 介紹
Spring Boot OAuth2.0是Spring Security的一個擴展庫,它可以讓我們輕鬆地使用Spring Boot來實現認證和授權。使用Spring Boot OAuth2.0,可以用Access Token來保護我們的API,使得我們的API接口越來越開發友好。這使得Spring Boot為開發者提供了一種實現OAuth2.0的快速方法。
三、Spring Boot OAuth2.0的安裝
使用Spring Boot OAuth2.0,需要添加spring-security-oauth2-client和spring-security-oauth2-resource-server庫。
添加依賴:
<dependencies>
<dependency>
<groupId>org.springframework.security.oauth.boot</groupId>
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth.boot</groupId>
<artifactId>spring-security-oauth2-client-autoconfigure</artifactId>
</dependency>
</dependencies>
四、Spring Boot OAuth2.0的使用
1. Client Credentials Grant Type 授權方式(客戶端授權模式)
此授權方式適用於第三方應用程序通過其客戶端票據來訪問受保護的API資源。
步驟一:配置application.yml
spring:
security:
oauth2:
client:
registration:
clientservice:
client-id: clientservice
client-secret: 123456
authorization-grant-type: client_credentials
scope: read
provider:
security:
token-uri: http://localhost:8080/oauth/token
步驟二:獲取Access Token
curl -XPOST -u username:password http://localhost:8080/oauth/token\?
grant_type=client_credentials\&client_id=clientservice\&client_secret=123456\&scope=read
步驟三:請求受保護的API資源
curl -XGET -H "Authorization:Bearer [ACCESS_TOKEN]" http://localhost:8080/api/resource
2. Authorization Code Grant Type 授權方式(授權碼模式)
此授權方式適用於需要用戶授權的APP。
步驟一:添加authorization server和resource server
@SpringBootApplication
@EnableAuthorizationServer
@EnableResourceServer
public class OAuth2Application {
public static void main(String[] args) {
SpringApplication.run(OAuth2Application.class, args);
}
步驟二:配置application.yml
spring:
security:
oauth2:
client:
registration:
clientservice:
client-id: clientservice
client-secret: 123456
authorization-grant-type: authorization_code
redirect-uri: "{baseUrl}/{action}/oauth2/code/{registrationId}"
scope:
- read
provider:
security:
token-uri: http://localhost:8080/oauth/token
authorization-uri: http://localhost:8080/oauth/authorize
jwk-set-uri: http://localhost:8080/.well-known/jwks.json
步驟三:用戶授權,獲取code
http://localhost:8080/oauth/authorize?client_id=clientservice&response_type=code
步驟四:獲取Access Token
curl http://localhost:8080/oauth/token -d "grant_type=authorization_code&code=[CODE]&client_id=clientservice&client_secret=123456" -X POST
步驟五:請求受保護的API資源
curl -XGET -H "Authorization:Bearer [ACCESS_TOKEN]" http://localhost:8080/api/resource
五、總結
Spring Boot OAuth2.0是一個功能強大的授權框架,可以快速幫助開發者實現認證和授權的功能。本文介紹了Client Credentials Grant Type和Authorization Code Grant Type兩種授權方式的實現。開發者可根據實際情況選擇合適的授權方式來使用。
原創文章,作者:WEVTH,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/369979.html