OAuth2 授权(第三方应用)
Vocnet 使用 OAuth 2.0 授权码模式(Authorization Code Flow)。第三方应用通过用户授权获取 access_token,随后以 Bearer Token 调用 API。
术语
BASE_URL:你的 vocnet 实例地址(例如https://vocnet.apps.tftt.cc或http://localhost:8080)client_id/client_secret:开发者应用凭证access_token:调用 API 的短期凭证refresh_token:刷新access_token的长期凭证(如实例启用)
1) 申请并配置 OAuth 应用
创建应用时通常需要配置:
- 应用名称/描述
redirect_uri(必须与后续请求完全一致)- scopes(最小权限原则)
常见 scopes 示例:
words:read/words:writereview:read/review:writewordbooks:read/wordbooks:write
2) 引导用户授权
将用户跳转到:
{BASE_URL}/oauth/authorize?
client_id=YOUR_CLIENT_ID&
redirect_uri=https://your-app.com/callback&
response_type=code&
scope=words:read words:write&
state=RANDOM_STATE_STRING
你需要在发起授权请求前生成并保存 state,回调时校验一致性(防 CSRF)。
3) 接收回调并取到授权码
用户同意授权后,你会收到回调:
https://your-app.com/callback?code=AUTHORIZATION_CODE&state=RANDOM_STATE_STRING
4) 交换 access token
在你的后端交换 token(不要在前端/移动端暴露 client_secret):
curl -X POST {BASE_URL}/oauth/token \
-H 'Content-Type: application/x-www-form-urlencoded' \
-d 'grant_type=authorization_code' \
-d 'code=AUTHORIZATION_CODE' \
-d 'client_id=YOUR_CLIENT_ID' \
-d 'client_secret=YOUR_CLIENT_SECRET' \
-d 'redirect_uri=https://your-app.com/callback'
5) 调用 API
curl {BASE_URL}/api/v1/learning/learned-words \
-H 'Authorization: Bearer YOUR_ACCESS_TOKEN'
6) 刷新 token(如支持)
curl -X POST {BASE_URL}/oauth/token \
-H 'Content-Type: application/x-www-form-urlencoded' \
-d 'grant_type=refresh_token' \
-d 'refresh_token=YOUR_REFRESH_TOKEN' \
-d 'client_id=YOUR_CLIENT_ID' \
-d 'client_secret=YOUR_CLIENT_SECRET'
安全建议
client_secret只能放在你的后端- 必须校验
state - 用 HTTPS;token/refresh token 需要加密存储
- 处理好 401/403:token 过期、撤销授权、scope 不足