Files
huachuang/OAuth2-Token接口使用文档.md
2026-07-18 17:38:34 +08:00

4.5 KiB
Raw Permalink Blame History

OAuth2 Token 接口使用文档

接口地址

POST http://{域名}/system/oauth2/token
Content-Type: application/x-www-form-urlencoded

通用规则

  • 所有请求必须携带 HTTP Basic Auth 请求头:Authorization: Basic base64(client_id:secret)
  • 响应格式:{"code":0,"msg":"...","data":{...}}
  • code=0 表示成功
  • 默认客户端:client_id=defaultsecret=admin123

支持的授权模式

1. 客户端模式 client_credentials(外部系统调用推荐)

适用场景:机器对机器调用,无需用户登录。

curl -X POST "http://localhost:48080/system/oauth2/token" \
  -u "default:admin123" \
  -d "grant_type=client_credentials"

参数:

参数 必填 说明
grant_type 固定值 client_credentials
scope 授权范围,多个用空格分隔,如 read write

成功响应:

{
  "code": 0,
  "data": {
    "access_token": "a1b2c3d4-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
    "refresh_token": "r1r2r3r4-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
    "expires_in": 7200,
    "token_type": "bearer",
    "scope": "read write",
    "user_id": 0
  }
}

2. 密码模式 password

适用场景:用户直接用账号密码换取 token如移动端 App 登录)。

curl -X POST "http://localhost:48080/system/oauth2/token" \
  -u "default:admin123" \
  -d "grant_type=password" \
  -d "username=admin" \
  -d "password=admin123"

参数:

参数 必填 说明
grant_type 固定值 password
username 用户账号
password 用户密码
scope 授权范围,多个用空格分隔

3. 授权码模式 authorization_code

适用场景:第三方应用需要用户授权后才能访问用户数据(如 SSO 单点登录)。

分两步走:

第一步:用户浏览器访问授权页,拿到 code

浏览器访问:
http://localhost:48080/system/oauth2/authorize?clientId=default

用户确认授权后,回调地址会带上 code 参数。

第二步:用 code 换 token

curl -X POST "http://localhost:48080/system/oauth2/token" \
  -u "default:admin123" \
  -d "grant_type=authorization_code" \
  -d "code=xxxx" \
  -d "redirect_uri=https://回调地址" \
  -d "state=1"

参数:

参数 必填 说明
grant_type 固定值 authorization_code
code 第一步获取的授权码
redirect_uri 必须与第一步的回调地址一致
state 透传的状态值,用于防 CSRF

4. 刷新令牌 refresh_token

适用场景token 快过期时,用 refresh_token 换新 token无需重新登录。

curl -X POST "http://localhost:48080/system/oauth2/token" \
  -u "default:admin123" \
  -d "grant_type=refresh_token" \
  -d "refresh_token=r1r2r3r4-xxxx-xxxx-xxxx-xxxxxxxxxxxx"

参数:

参数 必填 说明
grant_type 固定值 refresh_token
refresh_token 之前获取的 refresh_token

其他接口

校验 Token

curl -X POST "http://localhost:48080/system/oauth2/check-token" \
  -u "default:admin123" \
  -d "token=要校验的access_token"

撤销 Token登出

curl -X DELETE "http://localhost:48080/system/oauth2/token?token=要撤销的access_token" \
  -u "default:admin123"

四种模式对比

模式 grant_type 值 是否需用户参与 适用场景
客户端模式 client_credentials 外部系统调用、定时任务、机器间通信
密码模式 password 是(提供账号密码) 移动端 App 登录、信任的客户端
授权码模式 authorization_code 是(浏览器确认授权) 第三方应用 SSO、开放平台
刷新令牌 refresh_token Token 续期,配合以上任意模式使用

外部系统完整调用流程

① 你在后台创建 OAuth2 客户端,拿到 client_id + secret
         │
② 外部系统用 client_credentials 模式换 token
   curl -u "client_id:secret" -d "grant_type=client_credentials"
         │
③ 拿到 access_token之后每个请求带上
   curl -H "Authorization: Bearer <access_token>" /admin-api/xxx
         │
④ token 过期前,用 refresh_token 续期
   curl -u "client_id:secret" -d "grant_type=refresh_token" -d "refresh_token=xxx"