# 認証 API リファレンス

マーケットプレイス版の認証エンドポイント仕様、JWT クレーム構造、エラーコードのリファレンスです。

## ベース URL

API のベース URL は次のとおりです。ただし、トークンの口（`/api/v1/auth/external-service-token`）と JWKS の口（`/.well-known/jwks.json`）は、認証サービスのドメイン（`<auth-domain>`）に送ります。ドメインは、構築の時に決めた値です。

Marketplace

`https://<your-domain>`

## 認証エンドポイント一覧

Marketplace

マーケットプレイス版は Client Credentials フローに対応した認証エンドポイントを提供します。サービスアカウントの認証情報でアクセストークンを取得し、API を利用します。

| メソッド | エンドポイント                               | 説明                                                 |
| ---- | ------------------------------------- | -------------------------------------------------- |
| POST | `/api/v1/auth/external-service-token` | トークンエンドポイント。Client Credentials フローでアクセストークンを発行します。 |
| GET  | `/.well-known/jwks.json`              | JWKS エンドポイント。JWT 署名検証用の公開鍵セットを返します。                |

> **サービスアカウントの作成**
>
> API を利用するには、管理コンソールでサービスアカウントを作成し、Client ID と Client Secret を取得してください。サービスアカウントの作成手順は管理コンソールのドキュメントを参照してください。

## Token エンドポイント

### POST`/api/v1/auth/external-service-token`

Client Credentials フローでアクセストークンを発行します。サービスアカウントの認証情報（Client ID / Client Secret）を使用して認証します。

### リクエストヘッダー

| ヘッダー           | 必須 | 説明                                                                                  |
| -------------- | -- | ----------------------------------------------------------------------------------- |
| `Content-Type` | —  | application/json。client\_id・client\_secret を JSON ボディで送るときは必要です（Basic 認証だけで送るときは不要） |

### リクエストボディ

| パラメータ           | 型        | 必須 | 説明                                   |
| --------------- | -------- | -- | ------------------------------------ |
| `client_id`     | `string` | 必須 | サービスアカウントの Client ID（管理コンソールで発行）     |
| `client_secret` | `string` | 必須 | サービスアカウントの Client Secret（管理コンソールで発行） |

### リクエスト例

**Get token (service account)**

**curl**

```curl
curl -X POST https://<auth-domain>/api/v1/auth/external-service-token \
-H "Content-Type: application/json" \
-d '{
  "client_id": "your_client_id",
  "client_secret": "your_client_secret"
}'
```

**Python**

```python
import requests

response = requests.post(
  "https://<auth-domain>/api/v1/auth/external-service-token",
  json={"client_id": "your_client_id", "client_secret": "your_client_secret"},
)

print(response.json())
```

**TypeScript**

```typescript
const response = await fetch("https://<auth-domain>/api/v1/auth/external-service-token", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
  client_id: "your_client_id",
  client_secret: "your_client_secret",
}),
});

const data = await response.json();
console.log(data);
```

**Go**

```go
payload, _ := json.Marshal(map[string]string{
  "client_id":     "your_client_id",
  "client_secret": "your_client_secret",
})
resp, _ := http.Post("https://<auth-domain>/api/v1/auth/external-service-token", "application/json", bytes.NewBuffer(payload))
defer resp.Body.Close()

var result map[string]interface{}
json.NewDecoder(resp.Body).Decode(&result)
fmt.Println(result)
```

### レスポンスフィールド（200 OK）

| フィールド          | 型         | 説明                  |
| -------------- | --------- | ------------------- |
| `success`      | `boolean` | リクエストの成否（成功時は true） |
| `access_token` | `string`  | JWT 形式のアクセストークン     |
| `token_type`   | `string`  | Bearer              |
| `expires_in`   | `number`  | アクセストークンの有効期限（秒）    |
| `scope`        | `string`  | 付与されたスコープ（スペース区切り）  |

### レスポンス例

```json
{
  "success": true,
  "access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "Bearer",
  "expires_in": 86400,
  "scope": "openid profile email"
}
```

> **注記**
>
> マーケットプレイス版ではリフレッシュトークンは発行されません。トークンの有効期限が切れた場合は、同じ手順で新しいトークンを取得してください。

### エラーレスポンス

| ステータス | code                  | 説明                                                         |
| ----- | --------------------- | ---------------------------------------------------------- |
| `400` | `missing_parameters`  | client\_id または client\_secret が不足                          |
| `401` | `auth_error`          | クライアント認証に失敗（Client ID / Secret が不正）                        |
| `429` | `rate_limit_exceeded` | 同じ送り元からの要求が多すぎる。時間をおいて再試行する（Retry-After ヘッダーがあれば、その秒数だけ待つ） |
| `500` | `server_error`        | サーバー内部エラー（認証基盤と通信できないときを含む）                                |

```json
{
  "success": false,
  "error": "認証情報が正しくありません",
  "message": "認証情報が正しくありません",
  "code": "auth_error"
}
```

## JWKS エンドポイント

### GET`/.well-known/jwks.json`

JWT 署名検証用の公開鍵セット（JSON Web Key Set）を返します。アクセストークンの署名を検証する場合に使用します。

### リクエスト例

**Get JWKS**

**curl**

```curl
curl https://<auth-domain>/.well-known/jwks.json
```

**Python**

```python
import requests

response = requests.get(
  "https://<auth-domain>/.well-known/jwks.json",
)

print(response.json())
```

**TypeScript**

```typescript
const response = await fetch("https://<auth-domain>/.well-known/jwks.json");
const data = await response.json();
console.log(data);
```

**Go**

```go
req, _ := http.NewRequest("GET", "https://<auth-domain>/.well-known/jwks.json", nil)
resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()

var result map[string]interface{}
json.NewDecoder(resp.Body).Decode(&result)
fmt.Println(result)
```

### レスポンスフィールド（200 OK）

| フィールド        | 型        | 説明                                  |
| ------------ | -------- | ----------------------------------- |
| `keys`       | `array`  | JWK（JSON Web Key）オブジェクトの配列          |
| `keys[].kid` | `string` | 鍵 ID。JWT ヘッダーの kid と照合して検証に使用する鍵を特定 |
| `keys[].kty` | `string` | 鍵タイプ（例: "RSA"）                      |
| `keys[].alg` | `string` | アルゴリズム（例: "RS256"）                  |
| `keys[].use` | `string` | 鍵の用途。"sig"（署名検証）                    |
| `keys[].n`   | `string` | RSA 公開鍵のモジュラス（Base64url エンコード）      |
| `keys[].e`   | `string` | RSA 公開鍵の指数（Base64url エンコード）         |

### レスポンスヘッダー

| ヘッダー            | 説明                    |
| --------------- | --------------------- |
| `Cache-Control` | `public, max-age=600` |

### レスポンス例

```json
{
  "keys": [
    {
      "kid": "...",
      "kty": "RSA",
      "alg": "RS256",
      "use": "sig",
      "n": "...",
      "e": "AQAB"
    }
  ]
}
```

> **注記**
>
> 鍵のローテーションが行われた場合、`kid`（Key ID）が変更されます。署名検証時は JWT ヘッダーの `kid` と一致する鍵を使用してください。鍵はキャッシュ可能ですが、定期的な再取得を推奨します。

## JWT クレーム構造

アクセストークンに含まれる JWT クレーム（ペイロード）の構造です。署名アルゴリズムは RS256 です。

### 標準クレーム

| クレーム    | 型        | 説明                                                 |
| ------- | -------- | -------------------------------------------------- |
| `sub`   | `string` | サービスアカウント ID（UUID）                                 |
| `iss`   | `string` | 発行者 URL（例: `https://<your-domain>/realms/<realm>`） |
| `aud`   | `string` | 固定値 `"account"`                                    |
| `exp`   | `number` | 有効期限（Unix タイムスタンプ）                                 |
| `iat`   | `number` | 発行日時（Unix タイムスタンプ）                                 |
| `jti`   | `string` | JWT ID。トークンを一意に識別する ID                             |
| `typ`   | `string` | トークン種別（"Bearer"）                                   |
| `azp`   | `string` | Authorized Party（トークンを要求したクライアント ID）               |
| `scope` | `string` | 付与されたスコープ（スペース区切り）                                 |
| `acr`   | `string` | 認証コンテキストクラス                                        |

### ユーザー情報

サービスアカウント作成時に認証基盤が自動生成する内部識別子です。実在のユーザーを表すものではないため、アプリケーション側で表示・利用する必要はありません。

| クレーム                 | 型         | 説明                         |
| -------------------- | --------- | -------------------------- |
| `email`              | `string`  | 認証基盤が付与する内部用の識別子           |
| `email_verified`     | `boolean` | 認証基盤が付与する内部用フラグ（常に `true`） |
| `preferred_username` | `string`  | 認証基盤が付与する内部用の識別子           |

### サービスアカウント情報

| クレーム            | 型        | 説明             |
| --------------- | -------- | -------------- |
| `client_id`     | `string` | クライアント ID      |
| `clientHost`    | `string` | リクエスト元ホスト      |
| `clientAddress` | `string` | リクエスト元 IP アドレス |

### ロール

認証基盤の内部制御で使われるロール情報です。アプリケーション側で参照する必要はありません。

| クレーム                            | 型          | 説明                       |
| ------------------------------- | ---------- | ------------------------ |
| `realm_access.roles`            | `string[]` | 認証基盤が付与する Realm 配下のロール一覧 |
| `resource_access.account.roles` | `string[]` | 認証基盤が付与するクライアント配下のロール一覧  |

### JWT Access Token Payload 例

```json
{
  "exp": 1776713919,
  "iat": 1776627519,
  "jti": "trrtcc:abc12345-6789-4def-8abc-0123456789ab",
  "iss": "https://<your-domain>/realms/<realm>",
  "aud": "account",
  "sub": "11111111-2222-3333-4444-555555555555",
  "typ": "Bearer",
  "azp": "my-service-account",
  "acr": "1",
  "realm_access": {
    "roles": ["..."]
  },
  "resource_access": {
    "account": {
      "roles": ["..."]
    }
  },
  "scope": "openid email profile",
  "email_verified": true,
  "clientHost": "192.168.1.100",
  "preferred_username": "service-account-my-service-account",
  "clientAddress": "192.168.1.100",
  "email": "my-service-account@serviceaccount.local",
  "client_id": "my-service-account"
}
```

## クライアント認証

トークンエンドポイントでは、以下のいずれかの方式でクライアント認証を行います。

### JSON ボディ

リクエストボディに `client_id` と `client_secret` を JSON で含めます。

```json
{"client_id": "xxx", "client_secret": "yyy"}
```

### Basic 認証（推奨）

Authorization ヘッダーに Basic 認証で送信します。リクエストボディは不要です。

```text
Authorization: Basic base64(client_id:client_secret)
```

### Basic 認証でのリクエスト例

```bash
curl -X POST https://<auth-domain>/api/v1/auth/external-service-token \
  -u "your_client_id:your_client_secret"
```

## エラーコード

認証エンドポイントは JSON 形式のエラーレスポンスを返します。すべてのエラーレスポンスには `success: false` が含まれます。

### エラーレスポンス形式

| フィールド     | 型         | 説明                  |
| --------- | --------- | ------------------- |
| `success` | `boolean` | 常に false            |
| `error`   | `string`  | エラーメッセージ            |
| `message` | `string`  | エラーメッセージ（error と同値） |
| `code`    | `string`  | エラーコード（機械処理用）       |

```json
{
  "success": false,
  "error": "client_id, client_secret は必須です",
  "message": "client_id, client_secret は必須です",
  "code": "missing_parameters"
}
```

### エラーコード一覧

| ステータス | code                  | 説明                                                         |
| ----- | --------------------- | ---------------------------------------------------------- |
| `400` | `missing_parameters`  | 必須パラメータ（client\_id / client\_secret）が不足                    |
| `401` | `auth_error`          | クライアント認証に失敗（Client ID / Secret が不正）                        |
| `429` | `rate_limit_exceeded` | 同じ送り元からの要求が多すぎる。時間をおいて再試行する（Retry-After ヘッダーがあれば、その秒数だけ待つ） |
| `500` | `server_error`        | サーバー内部エラー（認証基盤と通信できないときを含む）                                |
