
什么是 REST API?
>
> 在 CI/CD 中無縫集成API 自動化測試與合規(guī)掃描
> 通過 Token 刷新 與 吊銷機制,提升安全可控性
> * 采用 PKCE、HTTP-only Cookie 等手段防范常見 Web 攻擊
授權(quán)碼模式(Authorization Code Grant)
客戶端憑證模式(Client Credentials Grant)
隱式模式(Implicit Grant)(已棄用)
資源所有者密碼模式(Password Grant)
flowchart LR
A[客戶端] -- > |1. 請求授權(quán)| B[授權(quán)服務(wù)器]
B -- > |2. 登錄&同意| C[用戶]
B -- > |3. 返回授權(quán)碼(code)| A
A -- > |4. 交換令牌| B
B -- > |5. 返回Access+Refresh Token| A
A -- > |6. 帶Token訪問資源服務(wù)器| D[資源服務(wù)器]
D -- > |7. 驗證Token并返回數(shù)據(jù)| A
> 長尾關(guān)鍵詞:如何使用 OAuth2 Authorization Code,OAuth2 PKCE 教程
JWT(JSON Web Token)由三部分組成,用點號分隔:
Header.Payload.Signature
sub
、iss
、exp
、aud
、roles
)。優(yōu)勢
注意
> 相關(guān)關(guān)鍵詞:JWT 結(jié)構(gòu)解析,如何安全存儲 JWT
將 OAuth2 的 Access Token 定義為 JWT,可讓資源服務(wù)器 本地驗證,提高性能與可用性。流程要點:
/token
Endpoint 簽發(fā) JWT 形式的 Access Token。iss
、aud
、exp
等字段與公鑰(JWKs)進行本地解密與驗證。> 長尾關(guān)鍵詞:OAuth2 JWT 集成,JWT Token 刷新與吊銷
下面以 Spring Boot 3 為例,演示如何快速構(gòu)建一個基于 OAuth2 授權(quán)碼 + JWT 的安全微服務(wù)。
< 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-oauth2-client < /artifactId >
< /dependency >
application.yml
spring:
security:
oauth2:
client:
registration:
my-client:
client-id: your-client-id
client-secret: your-secret
authorization-grant-type: authorization_code
redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
scope: openid,profile,email
provider:
my-provider:
authorization-uri: https://auth.example.com/oauth2/authorize
token-uri: https://auth.example.com/oauth2/token
user-info-uri: https://auth.example.com/userinfo
resourceserver:
jwt:
jwk-set-uri: https://auth.example.com/.well-known/jwks.json
@EnableWebSecurity
public class SecurityConfig {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth - > auth
.antMatchers("/public/**").permitAll()
.anyRequest().authenticated())
.oauth2Login(withDefaults())
.oauth2ResourceServer(oauth2 - > oauth2
.jwt(withDefaults()));
return http.build();
}
}
@RestController
public class UserController {
@GetMapping("/me")
public Map < String, Object > getProfile(@AuthenticationPrincipal Jwt jwt) {
return Map.of(
"username", jwt.getSubject(),
"roles", jwt.getClaimAsStringList("roles")
);
}
}
> 核心關(guān)鍵詞:Spring Boot OAuth2 JWT 教程,Spring Security OAuth2 實戰(zhàn)
X-CSRF-Token
,鑒別來源。對 SPA 和原生應(yīng)用,必須使用 PKCE:
client → generate code_verifier & code_challenge → auth request with code_challenge
auth server → return code → client redeem code with code_verifier
> 長尾關(guān)鍵詞:OAuth2 PKCE 教程,SPA Token 安全存儲
以 Python FastAPI 為例,快速搭建 OAuth2 密碼模式+JWT 驗證:
from fastapi import FastAPI, Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
import jwt, time
app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
@app.post("/token")
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
# 驗證用戶名/密碼
access_token = jwt.encode(
{"sub": form_data.username, "exp": time.time()+600},
"secret_key", algorithm="HS256"
)
return {"access_token": access_token, "token_type": "bearer"}
@app.get("/users/me")
async def read_users_me(token: str = Depends(oauth2_scheme)):
try:
payload = jwt.decode(token, "secret_key", algorithms=["HS256"])
except jwt.PyJWTError:
raise HTTPException(status_code=401, detail="Token 無效")
return {"username": payload["sub"]}
> 相關(guān)關(guān)鍵詞:FastAPI OAuth2 JWT 示例,Python API 身份驗證
roles
、scopes
,并在資源服務(wù)器精確校驗。id_token
與用戶信息。> 相關(guān)關(guān)鍵詞:Token 吊銷機制,JWT Key Rotation,OIDC vs OAuth2
在 Jenkins、GitLab CI 或 GitHub Actions 中,通常會:
/token
Endpoint;exp
、aud
、iss
等 Claim;stage('獲取Token') {
steps {
script {
TOKEN = sh(returnStdout: true, script: '''
curl -X POST https://auth.test.com/oauth2/token \
-d grant_type=client_credentials \
-u client_id:client_secret
''').trim()
}
}
}
stage('接口測試') { /* 使用 $TOKEN 調(diào)用接口 */ }
> 長尾關(guān)鍵詞:CI/CD OAuth2 自動化測試,API 合規(guī)掃描
結(jié)語:通過本文,你已全面掌握 API 身份驗證與授權(quán) 的核心機制,能夠在項目中靈活應(yīng)用 OAuth2 授權(quán)碼、JWT 無狀態(tài)令牌、PKCE、Token 吊銷 等技術(shù),并在 CI/CD 中實現(xiàn)自動化與合規(guī)測試。立即動手搭建安全可靠的 API 授權(quán)體系,為你的系統(tǒng)保駕護航!