
如何獲取免費(fèi)的ChatGPT API密鑰 – Apidog
授權(quán)碼模式(Authorization Code Grant)
客戶端憑證模式(Client Credentials Grant)
隱式模式(Implicit Grant)(已棄用)
資源所有者密碼模式(Password Grant)
flowchart LR
A[客戶端] -- > |1. 請(qǐng)求授權(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èn)資源服務(wù)器| D[資源服務(wù)器]
D -- > |7. 驗(yàn)證Token并返回?cái)?shù)據(jù)| A
長(zhǎng)尾關(guān)鍵詞:如何使用 OAuth2 Authorization Code,OAuth2 PKCE 教程
JWT(JSON Web Token)由三部分組成,用點(diǎn)號(hào)分隔:
Header.Payload.Signature
sub
、iss
、exp
、aud
、roles
)。優(yōu)勢(shì)
注意
相關(guān)關(guān)鍵詞:JWT 結(jié)構(gòu)解析,如何安全存儲(chǔ) JWT
將 OAuth2 的 Access Token 定義為 JWT,可讓資源服務(wù)器 本地驗(yàn)證,提高性能與可用性。流程要點(diǎn):
/token
Endpoint 簽發(fā) JWT 形式的 Access Token。iss
、aud
、exp
等字段與公鑰(JWKs)進(jìn)行本地解密與驗(yàn)證。長(zhǎng)尾關(guān)鍵詞:OAuth2 JWT 集成,JWT Token 刷新與吊銷
下面以 Spring Boot 3 為例,演示如何快速構(gòu)建一個(gè)基于 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 實(shí)戰(zhàn)
X-CSRF-Token
,鑒別來(lái)源。對(duì) 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
長(zhǎng)尾關(guān)鍵詞:OAuth2 PKCE 教程,SPA Token 安全存儲(chǔ)
以 Python FastAPI 為例,快速搭建 OAuth2 密碼模式+JWT 驗(yàn)證:
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()):
# 驗(yàn)證用戶名/密碼
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 無(wú)效")
return {"username": payload["sub"]}
相關(guān)關(guān)鍵詞:FastAPI OAuth2 JWT 示例,Python API 身份驗(yàn)證
roles
、scopes
,并在資源服務(wù)器精確校驗(yàn)。id_token
與用戶信息。相關(guān)關(guān)鍵詞:Token 吊銷機(jī)制,JWT Key Rotation,OIDC vs OAuth2
在 Jenkins、GitLab CI 或 GitHub Actions 中,通常會(huì):
/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('接口測(cè)試') { /* 使用 $TOKEN 調(diào)用接口 */ }
長(zhǎng)尾關(guān)鍵詞:CI/CD OAuth2 自動(dòng)化測(cè)試,API 合規(guī)掃描
結(jié)語(yǔ):通過(guò)本文,你已全面掌握 API 身份驗(yàn)證與授權(quán) 的核心機(jī)制,能夠在項(xiàng)目中靈活應(yīng)用 OAuth2 授權(quán)碼、JWT 無(wú)狀態(tài)令牌、PKCE、Token 吊銷 等技術(shù),并在 CI/CD 中實(shí)現(xiàn)自動(dòng)化與合規(guī)測(cè)試。立即動(dòng)手搭建安全可靠的 API 授權(quán)體系,為你的系統(tǒng)保駕護(hù)航!
如何獲取免費(fèi)的ChatGPT API密鑰 – Apidog
確保性能與安全的9種API測(cè)試類型
API客戶端終極指南:優(yōu)勢(shì)、最佳實(shí)踐… – Testfully
最佳后端開發(fā)者API工具:終極指南 – Apidog
API安全:Python開發(fā)者最佳實(shí)踐 | 第一部分
如何使用 OpenAI 的 Sora API:綜合使用指南
API 設(shè)計(jì)原理:從理論到實(shí)踐
什么是 API Key 密鑰以及如何使用它們?
實(shí)測(cè):阿里云百煉上線「全周期 MCP 服務(wù)」,AI 工具一站式托管
對(duì)比大模型API的內(nèi)容創(chuàng)意新穎性、情感共鳴力、商業(yè)轉(zhuǎn)化潛力
一鍵對(duì)比試用API 限時(shí)免費(fèi)