Add oauth.md

This commit is contained in:
2025-07-30 02:45:28 +00:00
parent 015100807b
commit 0823357466

110
oauth.md Normal file
View File

@ -0,0 +1,110 @@
# OAuth 2.0 授权码流程Authorization Code Flow
## 角色定义
- **资源拥有者Resource Owner**:最终用户。
- **客户端Client**:请求资源的应用程序。
- **授权服务器Authorization Server**:负责验证用户并发放令牌。
- **资源服务器Resource Server**:提供受保护资源的 API。
---
## 步骤一:引导用户进行授权
客户端构造如下 URL引导用户跳转至授权服务器
```
GET /authorize?
response_type=code&
client_id=CLIENT_ID&
redirect_uri=REDIRECT_URI&
scope=read write&
state=STATE
```
> 用户登录并授权客户端访问其资源。
---
## 步骤二:授权服务器返回授权码
授权服务器将用户重定向回客户端,附带授权码:
```
GET REDIRECT_URI?code=AUTH_CODE&state=STATE
```
---
## 步骤三:客户端使用授权码换取访问令牌
客户端使用授权码向授权服务器发起 POST 请求:
```
POST /token
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code&
code=AUTH_CODE&
redirect_uri=REDIRECT_URI&
client_id=CLIENT_ID&
client_secret=CLIENT_SECRET
```
---
## 步骤四:授权服务器返回访问令牌
授权服务器返回 JSON 响应:
```json
{
"access_token": "ACCESS_TOKEN",
"token_type": "Bearer",
"expires_in": 3600,
"refresh_token": "REFRESH_TOKEN"
}
```
---
## 步骤五:客户端使用访问令牌访问资源
客户端通过 `Authorization` 请求头访问受保护资源:
```
GET /userinfo
Authorization: Bearer ACCESS_TOKEN
```
---
## 步骤六(可选):使用刷新令牌换取新令牌
当 access_token 过期后,客户端可以使用 refresh_token 获取新的令牌:
```
POST /token
Content-Type: application/x-www-form-urlencoded
grant_type=refresh_token&
refresh_token=REFRESH_TOKEN&
client_id=CLIENT_ID&
client_secret=CLIENT_SECRET
```
---
## 流程简图(文字表示)
```
Client ──> [GET /authorize] ──> Auth Server ──> 用户授权
redirect_uri?code=xxx
Client ──> [POST /token] ──> Auth Server ──> access_token
Client ──> [GET /resource] ──> Resource Server
```
---