OAuth 2.1 · OIDC

适用于 Web 应用与带后端的机密客户端。用户在浏览器完成登录与授权后,应用使用授权码换取令牌,再调用 UserInfo 或校验 ID Token。

前置条件

  • 已开通客户端,持有 client_id 与 client_secret。
  • redirect_uri 已在客户端登记,且通过规则校验。
  • 新建客户端默认开启 PKCE(S256)与 Refresh Token 轮换。
  • Token 端点认证方式:client_secret_basic 或 client_secret_post。

时序

  1. 应用生成高熵 code_verifier,计算 code_challenge = BASE64URL(SHA256(verifier))。
  2. 浏览器 302 跳转授权端点(携带 state 与 PKCE 参数)。
  3. 用户登录;若开启 consent,则确认授权范围。
  4. 河岸边通行证回跳 redirect_uri,携带 code 与 state。
  5. 应用后端用 code + verifier + 客户端凭证换取 token。
  6. 使用 access_token 调用 UserInfo;可选校验 id_token(OIDC)。

1. 授权请求

GET https://login.heanbian.com/oauth2/authorize
参数 必填 说明
response_type 是 固定为 code
client_id 是 已登记客户端 ID
redirect_uri 是 必须与登记值完全一致
scope 是 空格分隔,如 openid profile email
state 强烈建议 防 CSRF;回调时原样返回并校验
code_challenge 是(默认) PKCE challenge
code_challenge_method 是 仅支持 S256
GET https://login.heanbian.com/oauth2/authorize?response_type=code&client_id=<client_id>&redirect_uri=<redirect_uri>&scope=openid%20profile%20email&state=<state>&code_challenge=<challenge>&code_challenge_method=S256

2. 换取令牌

POST https://login.heanbian.com/oauth2/token

Content-Type: application/x-www-form-urlencoded。推荐使用 HTTP Basic(client_secret_basic):

curl -u '<client_id>:<client_secret>' \
  -d 'grant_type=authorization_code' \
  -d 'code=<code>' \
  -d 'redirect_uri=<redirect_uri>' \
  -d 'code_verifier=<verifier>' \
  https://login.heanbian.com/oauth2/token
参数 必填 说明
grant_type 是 authorization_code
code 是 授权回调返回的一次性授权码
redirect_uri 是 必须与授权请求一致
code_verifier 是 与 challenge 对应的原始 verifier

成功响应通常包含 access_token、token_type、expires_in、refresh_token;申请 openid 时另含 id_token。

3. 用户信息

GET https://login.heanbian.com/userinfo
curl -H 'Authorization: Bearer <access_token>' \
  https://login.heanbian.com/userinfo
兼容端点:https://login.heanbian.com/oauth2/userinfo。新接入请优先使用标准路径 /userinfo。声明按 access token 的 scope 过滤,详见 Scopes 与声明。

4. 刷新令牌

curl -u '<client_id>:<client_secret>' \
  -d 'grant_type=refresh_token' \
  -d 'refresh_token=<refresh_token>' \
  https://login.heanbian.com/oauth2/token
轮换策略:默认不复用 refresh token。每次刷新请保存响应中的新 refresh_token,旧值将失效。

回调 URI 规则

  • 仅允许 https / http。
  • http 仅用于本地开发(localhost / 环回地址)。
  • 禁止 URI 中的 userinfo 与 fragment。
  • 自检:POST /api/v1/integration/validate-redirect,body 示例 {"uri":"...","type":"redirect"}。

安全要求

  • 始终校验回调 state。
  • 授权码一次性使用,勿在前端长期保存 client_secret / code_verifier 以外的敏感凭证。
  • 校验 ID Token 的 iss、aud、exp,密钥来自 https://login.heanbian.com/oauth2/jwks。
  • 已注销 / 停用 / 锁定用户将无法通过 UserInfo 或继续签发有效会话相关令牌消费。