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 分で、1 回のみ使用でき、使用後は即座に無効になります。


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。QR コードを生成できます
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 のそれぞれについてこのエンドポイントを 1 回ずつ呼び出すことを推奨します。
  • 「セッションの一覧/全取り消し」API は提供しません。ユーザー単位の一括強制ログアウトが必要な場合は第 2 フェーズで追加します。

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