Nexith OAuth2 / OIDC API Documentation
Version: v1.0 · Updated: 2026-08-06
Service:nexith-api(Rust / Axum)
Algorithm: RS256 (RSA-2048)
Table of contents#
- Environment and Base URL
- Fixed parameters
- OIDC Discovery
- JWKS public key
- PKCE authorization code flow
- Device Code flow
- Refresh Token
- Userinfo
- Using an access token
- Error format
- Quick test scripts
Environment and Base URL#
| Environment | Base URL | Notes |
|---|---|---|
| Development (local machine) | http://auth.nexith.ai |
Via Caddy → localhost:8081 |
| Development (direct) | http://localhost:8081 |
Skips Caddy; equivalent |
| Production | https://auth.nexith.ai |
TLS terminated by Caddy |
auth.nexith.ai and api.nexith.ai point to the same nexith-api process (port 8081); Caddy
routes by domain, and both can be used to call the OAuth endpoints.
Fixed parameters#
client_id = b1a00492-073a-47ea-816f-4c329264a828The current version is a public client (no client_secret); the token endpoint requires no client authentication.
Allowed redirect_uri allowlist:
| Pattern | Purpose |
|---|---|
http://127.0.0.1:*/callback |
CLI local callback (any port) |
http://localhost:*/callback |
CLI local callback |
https://platform.nexith.ai/auth/callback |
Web platform |
Partner client (Nexith Forge)#
The platform can optionally enable a separate public client (display name Nexith Forge) for
desktop client OAuth login:
client_idis delivered out of band and is not written to the repository or documentation; the server configures it throughOAUTH__FORGE_CLIENT_ID, and leaving it empty means it is not enabled.- The loopback allowlist permits only
http://127.0.0.1:*. - Its traffic profile matches the existing public client (PKCE + device code + refresh rotation), and
the token's
audis that client_id.
OIDC Discovery#
GET /.well-known/openid-configuration#
No authentication required. The issuer and all endpoints are generated per environment:
APP_ENV=development gives http://auth.nexith.ai (local Caddy), while staging/production give
https://auth.nexith.ai.
curl http://auth.nexith.ai/.well-known/openid-configurationResponse 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 public key#
GET /.well-known/jwks.json#
Used to verify access_token / id_token signatures on the client; no authentication required.
curl http://auth.nexith.ai/.well-known/jwks.jsonResponse 200
{
"keys": [
{
"kty": "RSA",
"use": "sig",
"alg": "RS256",
"kid": "nexith-rs256-1",
"n": "iEk0_sk6inYtDmImiDKHXbap...",
"e": "AQAB"
}
]
}Signature verification example (Python, using 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 authorization code flow (recommended)#
Suited to CLI tools, desktop apps, and other scenarios where a local HTTP server can be started.
客户端 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: Generate PKCE parameters#
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#
Build the URL and open it in the system browser (CLIs typically invoke 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 parameters
| Parameter | Required | Description |
|---|---|---|
response_type |
✅ | Fixed to code |
client_id |
✅ | See Fixed parameters |
redirect_uri |
✅ | See the allowlist |
scope |
✅ | Space-separated; openid profile offline_access recommended |
code_challenge |
✅ | base64url(SHA-256(code_verifier)), without padding |
code_challenge_method |
✅ | Fixed to S256 |
state |
✅ | Client random value for CSRF protection; returned verbatim |
nonce |
Recommended | Random value; written into the id_token claim |
Response: returns an HTML login form (200); after the user enters email and password, the browser
automatically POSTs to /oauth2/authorize/submit.
Step 3: Receive the callback#
After successful authentication, the browser 303-redirects to redirect_uri:
http://127.0.0.1:PORT/callback?code=<AUTH_CODE>&state=<STATE>Validate
state: it must exactly match the value sent in Step 2, otherwise reject (CSRF protection).
AUTH_CODE is valid for 5 minutes, can be used only once, and is invalidated immediately after
use.
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>"Request parameters
| Parameter | Required | Description |
|---|---|---|
grant_type |
✅ | authorization_code |
code |
✅ | The AUTH_CODE received in Step 3 |
redirect_uri |
✅ | Must exactly match Step 2 |
client_id |
✅ | Fixed value |
code_verifier |
✅ | The original verifier generated in Step 1 (not the challenge) |
Response 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>"
}The id_token has the same structure as the access_token; both contain nonce, and both are
RS256-signed.
Device Code flow (headless / no browser)#
For SSH environments, CI/CD, headless servers, and other scenarios where a browser cannot be opened.
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"Request parameters
| Parameter | Required | Description |
|---|---|---|
client_id |
✅ | Fixed value |
scope |
No | Defaults to openid profile offline_access |
Response 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
}| Field | Description |
|---|---|
device_code |
Used when polling the token endpoint; not shown to the user |
user_code |
8 characters (XXXX-XXXX), shown to the user to enter in the browser |
verification_uri |
The URL the user is told to visit |
verification_uri_complete |
Full URL including the user_code; can be rendered as a QR code |
expires_in |
device_code lifetime (seconds); 600s = 10 minutes |
interval |
Recommended polling interval (seconds) |
POST /oauth2/token (device_code polling)#
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"Polling status reference
| HTTP | error |
Meaning | Client action |
|---|---|---|---|
| 400 | authorization_pending |
The user has not acted yet | Wait interval seconds, then retry |
| 400 | slow_down |
Polling too fast | Add 5s to the interval, then retry |
| 400 | access_denied |
The user denied authorization | Stop and inform the user |
| 400 | expired_token |
device_code has expired | Restart the flow |
| 200 | — | Authorization succeeded | Save the tokens and stop polling |
Successful authorization response 200 (same as 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#
After the user visits https://nexith.ai/activate in a browser, the page logs in and calls this
endpoint to complete authorization.
Requires: the logged-in user's Bearer token (obtained via /auth/login or 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"}'Response 200
{ "status": "authorized" }Errors
{ "error": "invalid_user_code", "message": "user_code not found or expired" }Refresh token rotation#
Each use of a refresh_token returns a new access_token and a new refresh_token, and the old refresh_token is revoked immediately (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"Response 200
{
"access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9...",
"token_type": "Bearer",
"expires_in": 3600,
"refresh_token": "new-refresh-token-uuid",
"scope": "openid profile offline_access"
}⚠️ Reusing an old refresh_token is rejected; the server returns
invalid_grant: refresh token revoked. Always persist the newest refresh_token locally.
Refresh token lifetime: 30 days (inactivity beyond 30 days requires logging in again).
POST /oauth2/revoke (token revocation, RFC 7009)#
For user logout / device unbinding. Returns 200 whether or not the token exists (validity is not leaked).
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>"Behavior:
- refresh token (not a JWT): sets
revoked_atinoauth_refresh_tokens; afterwardsgrant_type=refresh_tokenreturnsinvalid_grant: refresh token revoked. Whenclient_idis supplied, it must match the one used at issuance. - access token (JWT): a stateless signature cannot be invalidated directly, so the platform
writes it to a Redis blacklist (
oauth:revoked:jti:<jti>) until the token expires naturally (≤1h). Every verification point (API, Gateway, userinfo) checks this blacklist; on Redis failure it fails open, relying on the 1h expiry as a backstop. - On logout, clients should call this endpoint once for the access token and once for the refresh token.
- There is no "list/revoke all sessions" endpoint; bulk per-user revocation is planned for a later phase.
GET /oauth2/userinfo#
curl http://auth.nexith.ai/oauth2/userinfo \
-H "Authorization: Bearer <access_token>"Response 200
{
"sub": "42",
"userId": 42,
"email": "user@example.com",
"name": "张三",
"teamId": null,
"codingDataRetentionOptOut": true
}| Field | Type | Description |
|---|---|---|
sub |
string | User ID (as a string, per the OIDC spec) |
userId |
number | User ID (numeric, convenient for direct use) |
email |
string | Registration email |
name |
string | Display name |
teamId |
null | Reserved; always null at present |
codingDataRetentionOptOut |
boolean | Always true |
Using an access token#
An access_token can be used directly to call all Nexith API endpoints, fully equivalent to API key authentication:
# 查看个人信息
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 lifetime: 1 hour (3600s). Renew with the refresh_token before expiry; no re-login is needed.
Error format#
All error responses share the same format:
{
"error": "<error_code>",
"error_description": "<人类可读描述>"
}Error code reference
error |
HTTP | Description |
|---|---|---|
invalid_client |
400 | Incorrect client_id |
invalid_grant |
400 | code / refresh_token / device_code is invalid, expired, or already used |
invalid_request |
400 | Missing required parameters |
unsupported_grant_type |
400 | Unsupported grant_type |
authorization_pending |
400 | Device Code: the user has not authorized yet; keep polling |
slow_down |
400 | Device Code: polling too fast; increase the interval |
access_denied |
400 | Device Code: the user denied authorization |
expired_token |
400 | Device Code: device_code expired; start over |
server_error |
500 | Internal server error (Redis/DB unavailable, etc.) |
Quick test scripts#
The scripts below can be run directly if the hosts entries are configured locally.
Full Device Code flow#
#!/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
doneFull PKCE flow (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))Appendix: Scope reference#
| scope | Description |
|---|---|
openid |
Required; enables OIDC mode and returns an id_token |
profile |
Returns the name field (userinfo) |
email |
Returns the email field (userinfo) |
offline_access |
Returns a refresh_token, enabling long-term access |
If long-term access is not needed, offline_access can be omitted; no refresh_token is returned in
that case.
Nexith Platform — Internal API Documentation