NNexithDocs
状态控制台 ↗
概览与快速开始模型目录指南API 参考集成OAuth2 / OIDC

Nexith OAuth2 / OIDC 接口文档

版本:v1.0 · 更新:2026-08-06
服务:nexith-api(Rust / Axum)
算法:RS256(RSA-2048)


目录#


环境与 Base URL#

环境 Base URL 说明
开发(本机) http://auth.nexith.ai 经 Caddy → localhost:8081
开发(直连) http://localhost:8081 跳过 Caddy,等价
生产 https://auth.nexith.ai TLS 由 Caddy 终止

auth.nexith.ai 与 api.nexith.ai 指向同一个 nexith-api 进程(port 8081),Caddy 按域名分流,两者均可调用 OAuth 端点。


固定参数#

client_id = b1a00492-073a-47ea-816f-4c329264a828

当前版本为公开客户端(无 client_secret),token 端点无需客户端认证。

允许的 redirect_uri 白名单:

模式 用途
http://127.0.0.1:*/callback CLI 本地回调(任意端口)
http://localhost:*/callback CLI 本地回调
https://platform.nexith.ai/auth/callback Web 平台

合作方客户端(Nexith Forge)#

平台可以额外启用一个独立 public client(显示名 Nexith Forge),用于桌面客户端的 OAuth 登录:

  • client_id 线下交付,不写入仓库/文档;服务器通过 OAUTH__FORGE_CLIENT_ID 配置, 留空即未启用。
  • 回环白名单只放行 http://127.0.0.1:*。
  • 流量特征与现有公开 client 相同(PKCE + device code + refresh 轮换),token 的 aud 为该 client_id。

OIDC Discovery#

GET /.well-known/openid-configuration#

无需认证。issuer 与所有端点按环境生成:APP_ENV=development 为 http://auth.nexith.ai(本地 Caddy),staging/production 为 https://auth.nexith.ai。

curl http://auth.nexith.ai/.well-known/openid-configuration

响应 200

{
  "issuer": "https://auth.nexith.ai",
  "authorization_endpoint": "https://auth.nexith.ai/oauth2/authorize",
  "token_endpoint": "https://auth.nexith.ai/oauth2/token",
  "userinfo_endpoint": "https://auth.nexith.ai/oauth2/userinfo",
  "jwks_uri": "https://auth.nexith.ai/.well-known/jwks.json",
  "device_authorization_endpoint": "https://auth.nexith.ai/oauth2/device/code",
  "response_types_supported": ["code"],
  "grant_types_supported": [
    "authorization_code",
    "refresh_token",
    "urn:ietf:params:oauth:grant-type:device_code"
  ],
  "subject_types_supported": ["public"],
  "id_token_signing_alg_values_supported": ["RS256"],
  "scopes_supported": ["openid", "profile", "email", "offline_access"],
  "token_endpoint_auth_methods_supported": ["none"],
  "code_challenge_methods_supported": ["S256"]
}

JWKS 公钥#

GET /.well-known/jwks.json#

用于在客户端验证 access_token / id_token 签名,无需认证。

curl http://auth.nexith.ai/.well-known/jwks.json

响应 200

{
  "keys": [
    {
      "kty": "RSA",
      "use": "sig",
      "alg": "RS256",
      "kid": "nexith-rs256-1",
      "n": "iEk0_sk6inYtDmImiDKHXbap...",
      "e": "AQAB"
    }
  ]
}

验签示例(Python,使用 PyJWT):

import jwt, requests

jwks = requests.get("http://auth.nexith.ai/.well-known/jwks.json").json()
public_key = jwt.algorithms.RSAAlgorithm.from_jwk(jwks["keys"][0])

claims = jwt.decode(
    access_token,
    public_key,
    algorithms=["RS256"],
    audience="b1a00492-073a-47ea-816f-4c329264a828",
)

PKCE 授权码流程(推荐)#

适用于 CLI 工具、桌面应用等可以启动本地 HTTP 服务器的场景。

客户端                            auth.nexith.ai
  │                                      │
  │ 1. 生成 code_verifier / challenge     │
  │                                      │
  │── 2. 打开浏览器访问 /oauth2/authorize ─▶ 返回 HTML 登录页
  │                                      │
  │    [用户在浏览器填写邮箱 + 密码]        │
  │                                      │
  │◀── 3. 浏览器 303 跳转到 redirect_uri ──│
  │        ?code=AUTH_CODE&state=STATE   │
  │                                      │
  │── 4. POST /oauth2/token ────────────▶│
  │        grant_type=authorization_code │
  │        code=AUTH_CODE                │
  │        code_verifier=VERIFIER        │
  │◀── access_token + refresh_token ─────│

Step 1:生成 PKCE 参数#

Python

import os, hashlib, base64

code_verifier = base64.urlsafe_b64encode(os.urandom(32)).rstrip(b"=").decode()
code_challenge = base64.urlsafe_b64encode(
    hashlib.sha256(code_verifier.encode()).digest()
).rstrip(b"=").decode()
# code_challenge_method = "S256"

Rust

use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
use sha2::{Digest, Sha256};

let code_verifier: String = (0..32).map(|_| rand::random::<u8>())
    .collect::<Vec<_>>()
    .pipe(|b| URL_SAFE_NO_PAD.encode(b));

let code_challenge = URL_SAFE_NO_PAD.encode(Sha256::digest(code_verifier.as_bytes()));

Shell

CODE_VERIFIER=$(openssl rand -base64 32 | tr -d '=\n' | tr '+/' '-_')
CODE_CHALLENGE=$(printf '%s' "$CODE_VERIFIER" \
  | openssl dgst -sha256 -binary \
  | openssl base64 \
  | tr '+/' '-_' | tr -d '=')

Step 2:GET /oauth2/authorize#

构造 URL 并用系统浏览器打开(CLI 一般调用 open / xdg-open):

GET http://auth.nexith.ai/oauth2/authorize
  ?response_type=code
  &client_id=b1a00492-073a-47ea-816f-4c329264a828
  &redirect_uri=http%3A%2F%2F127.0.0.1%3APORT%2Fcallback
  &scope=openid%20profile%20offline_access
  &code_challenge=<CODE_CHALLENGE>
  &code_challenge_method=S256
  &state=<RANDOM_STATE>
  &nonce=<RANDOM_NONCE>

Query 参数

参数 必填 说明
response_type ✅ 固定 code
client_id ✅ 见固定参数
redirect_uri ✅ 见白名单
scope ✅ 空格分隔,建议 openid profile offline_access
code_challenge ✅ base64url(SHA-256(code_verifier)),无 padding
code_challenge_method ✅ 固定 S256
state ✅ 客户端随机值,防 CSRF,原样返回
nonce 推荐 随机值,会写入 id_token claim

响应: 返回 HTML 登录表单(200),用户填写邮密后浏览器自动 POST /oauth2/authorize/submit。


Step 3:接收回调#

用户认证成功后,浏览器 303 跳转到 redirect_uri:

http://127.0.0.1:PORT/callback?code=<AUTH_CODE>&state=<STATE>

验证 state:必须与 Step 2 发送的值完全一致,否则拒绝(防 CSRF)。

AUTH_CODE 有效期 5 分钟,只能使用一次,使用后立即失效。


Step 4:POST /oauth2/token(authorization_code)#

curl -s -X POST http://auth.nexith.ai/oauth2/token \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=authorization_code" \
  -d "code=<AUTH_CODE>" \
  -d "redirect_uri=http://127.0.0.1:PORT/callback" \
  -d "client_id=b1a00492-073a-47ea-816f-4c329264a828" \
  -d "code_verifier=<CODE_VERIFIER>"

请求参数

参数 必填 说明
grant_type ✅ authorization_code
code ✅ Step 3 收到的 AUTH_CODE
redirect_uri ✅ 必须与 Step 2 完全一致
client_id ✅ 固定值
code_verifier ✅ Step 1 生成的原始 verifier(不是 challenge)

响应 200

{
  "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9...",
  "token_type": "Bearer",
  "expires_in": 3600,
  "refresh_token": "88857201-5dfc-4449-a1b2-c3d4e5f60001",
  "scope": "openid profile offline_access",
  "id_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9..."
}

access_token Claims(RS256 JWT)

{
  "iss": "https://auth.nexith.ai",
  "aud": "b1a00492-073a-47ea-816f-4c329264a828",
  "sub": "42",
  "email": "user@example.com",
  "role": "user",
  "jti": "550e8400-e29b-41d4-a716-446655440000",
  "iat": 1754467200,
  "exp": 1754470800,
  "nonce": "<Step 2 发送的 nonce>"
}

id_token 结构与 access_token 相同,均含 nonce,均为 RS256 签名。


Device Code 流程(headless / 无浏览器)#

适用于 SSH 环境、CI/CD、无头服务器等无法打开浏览器的场景。

CLI(无浏览器)                auth.nexith.ai        用户浏览器
      │                              │                    │
      │── POST /oauth2/device/code ─▶│                    │
      │◀─ device_code + user_code ───│                    │
      │                              │                    │
      │  打印提示:                   │                    │
      │  "访问 https://nexith.ai/activate"               │
      │  "输入代码: XXXX-XXXX"        │                    │
      │                              │                    │
      │  每 5s 轮询:                 │                    │
      │── POST /oauth2/token ────────▶│                    │
      │◀─ authorization_pending ──────│                    │
      │                              │                    │
      │                              │◀── 用户登录 ────────│
      │                              │◀── 输入 user_code ──│
      │                              │─── 标记 authorized ▶│
      │                              │                    │
      │── POST /oauth2/token ────────▶│
      │◀─ access_token + refresh_token│

POST /oauth2/device/code#

curl -s -X POST http://auth.nexith.ai/oauth2/device/code \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "client_id=b1a00492-073a-47ea-816f-4c329264a828" \
  -d "scope=openid%20profile%20offline_access"

请求参数

参数 必填 说明
client_id ✅ 固定值
scope 否 默认 openid profile offline_access

响应 200

{
  "device_code": "0353629a-94a9-4714-ac44-2e7c54d6653c",
  "user_code": "985F-QAZZ",
  "verification_uri": "https://nexith.ai/activate",
  "verification_uri_complete": "https://nexith.ai/activate?user_code=985F-QAZZ",
  "expires_in": 600,
  "interval": 5
}
字段 说明
device_code 轮询 token 端点使用,不展示给用户
user_code 8 字符(XXXX-XXXX),展示给用户在浏览器输入
verification_uri 提示用户访问的 URL
verification_uri_complete 含 user_code 的完整 URL,可生成二维码
expires_in device_code 有效期(秒),600s = 10 分钟
interval 建议轮询间隔(秒)

POST /oauth2/token(device_code 轮询)#

curl -s -X POST http://auth.nexith.ai/oauth2/token \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=urn:ietf:params:oauth:grant-type:device_code" \
  -d "device_code=0353629a-94a9-4714-ac44-2e7c54d6653c" \
  -d "client_id=b1a00492-073a-47ea-816f-4c329264a828"

轮询状态对照

HTTP error 含义 客户端动作
400 authorization_pending 用户尚未操作 等待 interval 秒后重试
400 slow_down 轮询过快 间隔加 5s 后重试
400 access_denied 用户拒绝授权 终止,提示用户
400 expired_token device_code 已过期 重新发起流程
200 — 授权成功 保存 tokens,停止轮询

授权成功响应 200(同 authorization_code)

{
  "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9...",
  "token_type": "Bearer",
  "expires_in": 3600,
  "refresh_token": "28b8c060-3825-424e-9c3f-...",
  "scope": "openid profile offline_access"
}

POST /oauth2/device/activate#

用户在浏览器访问 https://nexith.ai/activate 后,页面登录并调用此接口完成授权。

需要:已登录用户的 Bearer token(通过 /auth/login 或 PKCE 获取)。

curl -s -X POST http://auth.nexith.ai/oauth2/device/activate \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer <user_access_token>" \
  -d '{"user_code": "985F-QAZZ"}'

响应 200

{ "status": "authorized" }

错误

{ "error": "invalid_user_code", "message": "user_code not found or expired" }

Refresh Token 轮换#

每次使用 refresh_token 返回新的 access_token 和 新的 refresh_token,旧 refresh_token 立即撤销(Token Rotation)。

curl -s -X POST http://auth.nexith.ai/oauth2/token \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=refresh_token" \
  -d "refresh_token=88857201-5dfc-4449-a1b2-c3d4e5f60001"

响应 200

{
  "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9...",
  "token_type": "Bearer",
  "expires_in": 3600,
  "refresh_token": "new-refresh-token-uuid",
  "scope": "openid profile offline_access"
}

⚠️ 重用旧 refresh_token 会被拒绝,服务端返回 invalid_grant: refresh token revoked。 请务必在本地持久化最新的 refresh_token。

Refresh token 有效期:30 天(不活跃超过 30 天需重新登录)。


POST /oauth2/revoke(Token 撤销,RFC 7009)#

用于用户登出 / 设备解绑。无论 token 是否存在都返回 200(不泄露有效性)。

curl -s -X POST http://auth.nexith.ai/oauth2/revoke \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "token=<access_token_or_refresh_token>" \
  -d "client_id=<client_id>"

行为:

  • refresh token(非 JWT):在 oauth_refresh_tokens 中置 revoked_at,之后 grant_type=refresh_token 返回 invalid_grant: refresh token revoked。 带 client_id 时要求与签发时一致。
  • access token(JWT):无状态签名无法直接作废,平台把它写入 Redis 黑名单 (oauth:revoked:jti:<jti>)直到 token 自然过期(≤1h)。所有校验点 (API、Gateway、userinfo)都会检查该黑名单;Redis 故障时 fail-open,靠 1h 过期兜底。
  • 客户端登出建议对 access token 与 refresh token 各调用一次本端点。
  • 不提供「列出/撤销全部会话」接口;如需按用户批量踢下线,二期再加。

GET /oauth2/userinfo#

curl http://auth.nexith.ai/oauth2/userinfo \
  -H "Authorization: Bearer <access_token>"

响应 200

{
  "sub": "42",
  "userId": 42,
  "email": "user@example.com",
  "name": "张三",
  "teamId": null,
  "codingDataRetentionOptOut": true
}
字段 类型 说明
sub string 用户 ID(字符串形式,符合 OIDC 规范)
userId number 用户 ID(数字形式,便于直接使用)
email string 注册邮箱
name string 显示名
teamId null 预留,当前始终为 null
codingDataRetentionOptOut boolean 始终为 true

Access Token 使用#

access_token 可以直接用于调用 所有 Nexith API 端点,与 API Key 鉴权完全等效:

# 查看个人信息
curl http://api.nexith.ai/v1/profile \
  -H "Authorization: Bearer <access_token>"

# 调用模型(Gateway,OpenAI 兼容)
curl http://gateway.nexith.ai/v1/chat/completions \
  -H "Authorization: Bearer <access_token>" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "nexith-core",
    "messages": [{"role": "user", "content": "hello"}],
    "stream": false
  }'

# 查看 API Keys
curl http://api.nexith.ai/v1/api-keys \
  -H "Authorization: Bearer <access_token>"

Token 有效期:1 小时(3600s)。到期前使用 refresh_token 续期,无需重新登录。


错误格式#

所有错误响应格式统一:

{
  "error": "<error_code>",
  "error_description": "<人类可读描述>"
}

错误码一览

error HTTP 说明
invalid_client 400 client_id 错误
invalid_grant 400 code / refresh_token / device_code 无效、已过期或已使用
invalid_request 400 缺少必填参数
unsupported_grant_type 400 grant_type 不支持
authorization_pending 400 Device Code:用户尚未授权,继续轮询
slow_down 400 Device Code:轮询过快,增大间隔
access_denied 400 Device Code:用户拒绝授权
expired_token 400 Device Code:device_code 已过期,需重新发起
server_error 500 服务内部错误(Redis/DB 不可用等)

快速测试脚本#

以下脚本在本机 hosts 已绑定的情况下可直接运行。

Device Code 完整流程#

#!/bin/bash
# 1. 申请 device code
RESP=$(curl -s -X POST http://auth.nexith.ai/oauth2/device/code \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "client_id=b1a00492-073a-47ea-816f-4c329264a828&scope=openid+profile+offline_access")

DEVICE_CODE=$(echo "$RESP" | python3 -c "import sys,json; print(json.load(sys.stdin)['device_code'])")
USER_CODE=$(echo "$RESP" | python3 -c "import sys,json; print(json.load(sys.stdin)['user_code'])")

echo "请访问:http://platform.nexith.ai/activate?user_code=$USER_CODE"
echo "或手动输入代码:$USER_CODE"
echo ""

# 2. 轮询(最多等 10 分钟)
for i in $(seq 1 120); do
  sleep 5
  TOKEN_RESP=$(curl -s -X POST http://auth.nexith.ai/oauth2/token \
    -H "Content-Type: application/x-www-form-urlencoded" \
    -d "grant_type=urn:ietf:params:oauth:grant-type:device_code" \
    -d "device_code=$DEVICE_CODE" \
    -d "client_id=b1a00492-073a-47ea-816f-4c329264a828")

  ERROR=$(echo "$TOKEN_RESP" | python3 -c "import sys,json; print(json.load(sys.stdin).get('error',''))" 2>/dev/null)

  if [ -z "$ERROR" ]; then
    echo "✅ 授权成功!"
    echo "$TOKEN_RESP" | python3 -m json.tool
    break
  elif [ "$ERROR" = "authorization_pending" ]; then
    echo "等待用户授权... ($i)"
  elif [ "$ERROR" = "slow_down" ]; then
    sleep 5
  else
    echo "❌ 错误: $ERROR"
    break
  fi
done

PKCE 完整流程(Python)#

import os, hashlib, base64, secrets, urllib.parse, urllib.request, json, webbrowser, http.server, threading

BASE = "http://auth.nexith.ai"
CLIENT_ID = "b1a00492-073a-47ea-816f-4c329264a828"
PORT = 9753
REDIRECT_URI = f"http://127.0.0.1:{PORT}/callback"

# 生成 PKCE 参数
code_verifier = base64.urlsafe_b64encode(os.urandom(32)).rstrip(b"=").decode()
code_challenge = base64.urlsafe_b64encode(
    hashlib.sha256(code_verifier.encode()).digest()).rstrip(b"=").decode()
state = secrets.token_urlsafe(8)
nonce = secrets.token_urlsafe(8)

# 用本地 HTTP 服务器接收回调
received_code = {}
class Handler(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        qs = urllib.parse.parse_qs(urllib.parse.urlparse(self.path).query)
        received_code["code"] = qs.get("code", [None])[0]
        received_code["state"] = qs.get("state", [None])[0]
        self.send_response(200)
        self.end_headers()
        self.wfile.write(b"Authorization complete. You can close this window.")
    def log_message(self, *args): pass

server = http.server.HTTPServer(("127.0.0.1", PORT), Handler)
t = threading.Thread(target=server.handle_request)
t.start()

# 打开浏览器
params = urllib.parse.urlencode({
    "response_type": "code", "client_id": CLIENT_ID,
    "redirect_uri": REDIRECT_URI, "scope": "openid profile offline_access",
    "code_challenge": code_challenge, "code_challenge_method": "S256",
    "state": state, "nonce": nonce,
})
webbrowser.open(f"{BASE}/oauth2/authorize?{params}")
print(f"已打开浏览器,等待登录...")
t.join()

assert received_code.get("state") == state, "state mismatch!"
auth_code = received_code["code"]

# 换取 tokens
body = urllib.parse.urlencode({
    "grant_type": "authorization_code", "code": auth_code,
    "redirect_uri": REDIRECT_URI, "client_id": CLIENT_ID,
    "code_verifier": code_verifier,
}).encode()
req = urllib.request.Request(f"{BASE}/oauth2/token", data=body,
      headers={"Content-Type": "application/x-www-form-urlencoded"})
with urllib.request.urlopen(req) as r:
    tokens = json.loads(r.read())

print(json.dumps(tokens, indent=2))

附:Scope 说明#

scope 说明
openid 必选,启用 OIDC 模式,返回 id_token
profile 返回 name 字段(userinfo)
email 返回 email 字段(userinfo)
offline_access 返回 refresh_token,支持长期访问

不需要长期访问时可省略 offline_access,此时不会返回 refresh_token。


Nexith Platform — Internal API Documentation