认证鉴权
OAuth 2.0 授权码模式
1. 引导用户授权
将用户重定向到授权页面:
GET https://auth.bglt.cn/oauth2/authorize
?client_id=<your_client_id>
&redirect_uri=<your_callback_url>
&response_type=code
&scope=read write
&state=<random_state>2. 获取授权码
用户完成登录授权后,认证系统将重定向到 redirect_uri 并携带授权码:
https://your-app.com/callback?code=<authorization_code>&state=<state>3. 换取访问令牌
使用授权码换取令牌:
http
POST https://auth.bglt.cn/oauth2/token
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code
&code=<authorization_code>
&redirect_uri=<your_callback_url>
&client_id=<your_client_id>
&client_secret=<your_client_secret>响应:
json
{
"access_token": "eyJhbGciOiJSUzI1NiIs...",
"token_type": "Bearer",
"expires_in": 3600,
"refresh_token": "dGhpcyBpcyBhIHJlZnJlc2g...",
"scope": "read write"
}客户端凭证模式
适用于服务器间调用:
http
POST https://auth.bglt.cn/oauth2/token
Content-Type: application/x-www-form-urlencoded
grant_type=client_credentials
&client_id=<your_client_id>
&client_secret=<your_client_secret>
&scope=readToken 管理
刷新令牌
访问令牌过期后,使用刷新令牌获取新的访问令牌:
http
POST https://auth.bglt.cn/oauth2/token
Content-Type: application/x-www-form-urlencoded
grant_type=refresh_token
&refresh_token=<refresh_token>
&client_id=<your_client_id>
&client_secret=<your_client_secret>撤销令牌
http
POST https://auth.bglt.cn/oauth2/revoke
Content-Type: application/x-www-form-urlencoded
token=<access_token_or_refresh_token>
&client_id=<your_client_id>
&client_secret=<your_client_secret>权限范围
| Scope | 说明 |
|---|---|
read | 读取数据权限 |
write | 写入数据权限 |
admin | 管理员权限 |
安全建议
- 始终使用 HTTPS 传输
- 客户端密钥仅在服务端使用,不要暴露到前端
- 设置合理的 Token 过期时间
- 使用
state参数防止 CSRF 攻击 - 定期轮换客户端密钥
