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 웹 플랫폼

파트너 클라이언트(Nexith Forge)#

플랫폼은 데스크톱 클라이언트의 OAuth 로그인용으로 별도의 public client(표시 이름 Nexith Forge)를 추가로 활성화할 수 있습니다:

  • 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), 사용자가 이메일/비밀번호를 입력하면 브라우저가 자동으로 /oauth2/authorize/submit에 POST합니다.


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, 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에 접속한 뒤, 페이지에서 로그인하고 이 API를 호출해 인증을 완료합니다.

필요: 로그인한 사용자의 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 각각에 대해 이 엔드포인트를 한 번씩 호출하는 것을 권장합니다.
  • "모든 세션 나열/폐기" 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 — 내부 API 문서