开放平台 OAuth
开放平台适合需要用户授权的服务端应用。先由站点账号创建应用,登记精确的回调地址与允许申请的 scope。client_secret 只在创建或轮换时返回;它必须保存在你的服务端。
授权流程按以下顺序完成:
- 为每次授权生成随机
code_verifier,计算 SHA-256 后做 base64url 编码,得到code_challenge。 - 将用户浏览器引导至
/v1/oauth2/authorize,传入response_type=code、client_id、登记的redirect_uri、申请的scope、code_challenge_method=S256与code_challenge。建议附上随机state并在回调时核对。 - 用户同意后,接入方服务端从回调取得一次性
code,用code_verifier、同一个redirect_uri和 client authentication 调用/v1/oauth2/token。 - 服务端保存返回的 access/refresh 凭据,仅把 access token 用于已获准的接口。刷新时替换旧 token 对;用户撤销授权后停止使用。
授权码有效期为 60 秒且只能兑换一次。access token 最长一小时,refresh family 有绝对 30 天期限;刷新不会延长这个上限。scope 可以缩小,不能扩大。/v1/oauth2/token 与 /v1/oauth2/revoke 使用专用 client authentication,不使用网站 Cookie/CSRF;应用管理和 consent 则仍走网站会话。
只有带 profile:read 和/或 email:read 的 OAuth access token 可以调用 userinfo。PAT 不提供这两个 scope。authorize、token 和 revoke 的协议错误返回 OAuth 的 { "error": "..." },不要按普通内容 API 的错误信封解析。scopes 和 userinfo 的错误使用普通映射 API 的 {error:{code,message}}。参数和响应见 OAuth API 参考。
服务端交换授权码的 TypeScript 示例。OAUTH_CODE 来自已核对 state 的回调,OAUTH_CODE_VERIFIER 是发起本次授权时保存的随机值;回调地址必须与登记及授权请求一致:
function required(name: string): string {
const value = process.env[name]
if (!value) throw new Error(`缺少 ${name}`)
return value
}
const response = await fetch('http://127.0.0.1:4520/v1/oauth2/token', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'authorization_code',
client_id: required('OAUTH_CLIENT_ID'),
client_secret: required('OAUTH_CLIENT_SECRET'),
code: required('OAUTH_CODE'),
code_verifier: required('OAUTH_CODE_VERIFIER'),
redirect_uri: 'https://example.com/oauth/callback',
}),
})
if (!response.ok) throw new Error(`兑换失败:${response.status} ${await response.text()}`)
const tokens = await response.json() as {
access_token: string; token_type: 'Bearer'; expires_in: number
refresh_token: string; scope: string
}
// 将 tokens 保存到服务端的安全存储;不要写入日志或交给浏览器。
同一请求的 curl 示例:
curl --fail-with-body 'http://127.0.0.1:4520/v1/oauth2/token' \
--data-urlencode 'grant_type=authorization_code' \
--data-urlencode "client_id=$OAUTH_CLIENT_ID" \
--data-urlencode "client_secret=$OAUTH_CLIENT_SECRET" \
--data-urlencode "code=$OAUTH_CODE" \
--data-urlencode "code_verifier=$OAUTH_CODE_VERIFIER" \
--data-urlencode 'redirect_uri=https://example.com/oauth/callback'
example.com 是占位回调,必须替换。参考中的 REPLACE_WITH_* 字符串也只是占位秘密,不能直接完成兑换;必须先执行真实的授权与 S256 PKCE 流程。选择 HTTP Basic 时应删除 body 中的 client_id/client_secret,不能同时使用两种 client authentication。
OAuth 接入使用 /v1/oauth2;申请权限前请以当前 scope 列表为准。令牌交换、刷新、撤销和内容写入不会自动重试;超时可能已经提交。刷新请求结果未知时不要盲目重放旧 refresh token,否则会触发整族撤销。