# 認証 API リファレンス

AGENTIC STAR SaaS版の OIDC エンドポイント仕様、JWT クレーム構造、スコープ、エラーコードのリファレンスです。

## ベース URL

すべてのエンドポイントは以下のベース URL に対して送信します。

SaaS

`https://auth.fd.agenticstar.tm.softbank.jp`

## Issuer

ID トークンの `iss` クレーム、および Discovery レスポンスの `issuer` に一致する値です。

SaaS

`https://auth.fd.agenticstar.tm.softbank.jp/realms/federation`

## エンドポイント一覧

SaaS

| メソッド       | エンドポイント                                               | 説明                                           |
| ---------- | ----------------------------------------------------- | -------------------------------------------- |
| GET        | `/realms/federation/.well-known/openid-configuration` | OpenID Connect Discovery エンドポイント             |
| GET        | `/federation/auth/v1/authorize`                       | Authorization Code フローのユーザー認可エンドポイント         |
| POST       | `/federation/auth/v1/token`                           | トークン取得エンドポイント（AC / CC / Refresh Token フロー対応） |
| GET / POST | `/federation/auth/v1/userinfo`                        | ユーザー情報取得エンドポイント（GET / POST 両対応）              |
| GET        | `/federation/auth/v1/jwks`                            | 公開鍵セット（JWKS）エンドポイント                          |
| POST       | `/federation/auth/v1/revoke`                          | トークン失効エンドポイント                                |

## Discovery

### GET`/realms/federation/.well-known/openid-configuration`

クライアントが必要なエンドポイント URL やサーバー情報を取得します。

互換用エイリアスとして、RFC 8414 (OAuth 2.0 Authorization Server Metadata) パスでも同一のレスポンスを返します:

```text
GET /realms/federation/.well-known/oauth-authorization-server
```

### リクエスト例

**Get discovery document**

**curl**

```curl
curl https://auth.fd.agenticstar.tm.softbank.jp/realms/federation/.well-known/openid-configuration
```

**Python**

```python
import requests

response = requests.get(
  "https://auth.fd.agenticstar.tm.softbank.jp/realms/federation/.well-known/openid-configuration",
)

print(response.json())
```

**TypeScript**

```typescript
const response = await fetch("https://auth.fd.agenticstar.tm.softbank.jp/realms/federation/.well-known/openid-configuration");
const data = await response.json();
console.log(data);
```

**Go**

```go
req, _ := http.NewRequest("GET", "https://auth.fd.agenticstar.tm.softbank.jp/realms/federation/.well-known/openid-configuration", nil)
resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()

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

### レスポンス例

```json
{
  "issuer": "https://auth.fd.agenticstar.tm.softbank.jp/realms/federation",
  "authorization_endpoint": "https://auth.fd.agenticstar.tm.softbank.jp/federation/auth/v1/authorize",
  "token_endpoint": "https://auth.fd.agenticstar.tm.softbank.jp/federation/auth/v1/token",
  "userinfo_endpoint": "https://auth.fd.agenticstar.tm.softbank.jp/federation/auth/v1/userinfo",
  "jwks_uri": "https://auth.fd.agenticstar.tm.softbank.jp/federation/auth/v1/jwks",
  "revocation_endpoint": "https://auth.fd.agenticstar.tm.softbank.jp/federation/auth/v1/revoke",
  "grant_types_supported": ["authorization_code", "refresh_token", "client_credentials"],
  "response_types_supported": ["code"],
  "response_modes_supported": ["query"],
  "subject_types_supported": ["public"],
  "id_token_signing_alg_values_supported": ["RS256"],
  "token_endpoint_auth_methods_supported": ["client_secret_basic", "client_secret_post"],
  "code_challenge_methods_supported": ["S256"]
}
```

### エラーレスポンス

| ステータス       | code              | 説明                                                              |
| ----------- | ----------------- | --------------------------------------------------------------- |
| 403         | `forbidden`       | 指定した realm が無い、または使えない realm を指定した（許可していないパスへの要求と同じ応答で、区別できません） |
| 4xx（404 以外） | `invalid_request` | 認証基盤が Discovery の取得を断った（認証基盤の 4xx の状態コードをそのまま返します）              |
| 502         | `bad_gateway`     | 認証基盤からの Discovery 文書の取得に失敗（認証基盤が 5xx を返した・つながらなかった）             |

## Authorization Code フロー

### GET`/federation/auth/v1/authorize`

ユーザーが認証してアプリケーションを認可し、Authorization Code を取得します。ウェブブラウザで直接アクセスしてください。

### クエリパラメータ

| パラメータ           | 型        | 必須 | 説明                                                                       |
| --------------- | -------- | -- | ------------------------------------------------------------------------ |
| `client_id`     | `string` | 必須 | クライアントID                                                                 |
| `redirect_uri`  | `string` | 必須 | 認可後にリダイレクトするURI（事前登録が必要）                                                 |
| `response_type` | `string` | 必須 | code を指定してください                                                           |
| `state`         | `string` | —  | 推奨。CSRF 対策用。クライアントが生成した予測不可能な値。指定した場合はレスポンスで返却されるため、リクエスト時の値と一致を検証してください |
| `nonce`         | `string` | —  | ID Token への nonce クレーム挿入用（推奨）                                            |

### リクエスト例

```bash
https://auth.fd.agenticstar.tm.softbank.jp/federation/auth/v1/authorize?\
  client_id=my-client&\
  redirect_uri=https%3A%2F%2Fapp.example.com%2Fcallback&\
  response_type=code&\
  state=abc123xyz&\
  nonce=xyz789abc
```

### レスポンス（302 Redirect）

ユーザーが認可に成功した場合、以下の形式でリダイレクトされます：

```text
https://app.example.com/callback?\
  code=AUTH_CODE&\
  state=abc123xyz
```

### エラーレスポンス

エラーが発生した場合、以下の形式でリダイレクトされます：

```text
https://app.example.com/callback?\
  error=invalid_scope&\
  error_description=...&\
  state=abc123xyz
```

| エラーコード                      | 説明                                                   |
| --------------------------- | ---------------------------------------------------- |
| `invalid_request`           | 必須パラメータが不足している、または形式が不正                              |
| `unauthorized_client`       | クライアントが認可フローを使用する権限がない                               |
| `unsupported_response_type` | `response_type` が `code` 以外の値（このサービスは `code` のみサポート） |
| `access_denied`             | クライアントが無効化されている、またはアクセスが拒否された                        |
| `invalid_scope`             | リクエストされたスコープが無効または不足                                 |
| `server_error`              | サーバー側のエラー                                            |

## Token エンドポイント

### POST`/federation/auth/v1/token`

Authorization Code フローまたは Client Credentials フローでアクセストークンを取得します。

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

| ヘッダー           | 必須 | 説明                                |
| -------------- | -- | --------------------------------- |
| `Content-Type` | 必須 | application/x-www-form-urlencoded |

### Authorization Code フロー

#### リクエストボディ

| パラメータ           | 型        | 必須 | 説明                                             |
| --------------- | -------- | -- | ---------------------------------------------- |
| `grant_type`    | `string` | 必須 | authorization\_code を指定                        |
| `code`          | `string` | 必須 | Authorization Code エンドポイントから取得した認可コード          |
| `redirect_uri`  | `string` | 必須 | Authorization Code 要求時に指定した redirect\_uri と同一値 |
| `client_id`     | `string` | 必須 | クライアントID                                       |
| `client_secret` | `string` | 必須 | クライアントシークレット（バックエンド間通信で安全に送信してください）            |

#### リクエスト例

**Get token (Authorization Code)**

**curl**

```curl
curl -X POST https://auth.fd.agenticstar.tm.softbank.jp/federation/auth/v1/token \
-d "grant_type=authorization_code" \
-d "code=AUTH_CODE" \
-d "redirect_uri=https://app.example.com/callback" \
-d "client_id=my-client" \
-d "client_secret=my-secret"
```

**Python**

```python
import requests

response = requests.post(
  "https://auth.fd.agenticstar.tm.softbank.jp/federation/auth/v1/token",
  data={"grant_type": "authorization_code", "code": "AUTH_CODE", "redirect_uri": "https://app.example.com/callback", "client_id": "my-client", "client_secret": "my-secret"},
)

print(response.json())
```

**TypeScript**

```typescript
const response = await fetch("https://auth.fd.agenticstar.tm.softbank.jp/federation/auth/v1/token", {
method: "POST",
body: new URLSearchParams({ grant_type: "authorization_code", code: "AUTH_CODE", redirect_uri: "https://app.example.com/callback", client_id: "my-client", client_secret: "my-secret" }),
});
const data = await response.json();
console.log(data);
```

**Go**

```go
form := url.Values{}
form.Set("grant_type", "authorization_code")
form.Set("code", "AUTH_CODE")
form.Set("redirect_uri", "https://app.example.com/callback")
form.Set("client_id", "my-client")
form.Set("client_secret", "my-secret")
resp, _ := http.PostForm("https://auth.fd.agenticstar.tm.softbank.jp/federation/auth/v1/token", form)
defer resp.Body.Close()

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

### Client Credentials フロー

#### リクエストボディ

| パラメータ           | 型        | 必須 | 説明                      |
| --------------- | -------- | -- | ----------------------- |
| `grant_type`    | `string` | 必須 | client\_credentials を指定 |
| `client_id`     | `string` | 必須 | クライアントID                |
| `client_secret` | `string` | 必須 | クライアントシークレット            |

#### リクエスト例

**Get token (Client Credentials)**

**curl**

```curl
curl -X POST https://auth.fd.agenticstar.tm.softbank.jp/federation/auth/v1/token \
-d "grant_type=client_credentials" \
-d "client_id=my-m2m-client" \
-d "client_secret=my-secret"
```

**Python**

```python
import requests

response = requests.post(
  "https://auth.fd.agenticstar.tm.softbank.jp/federation/auth/v1/token",
  data={"grant_type": "client_credentials", "client_id": "my-m2m-client", "client_secret": "my-secret"},
)

print(response.json())
```

**TypeScript**

```typescript
const response = await fetch("https://auth.fd.agenticstar.tm.softbank.jp/federation/auth/v1/token", {
method: "POST",
body: new URLSearchParams({ grant_type: "client_credentials", client_id: "my-m2m-client", client_secret: "my-secret" }),
});
const data = await response.json();
console.log(data);
```

**Go**

```go
form := url.Values{}
form.Set("grant_type", "client_credentials")
form.Set("client_id", "my-m2m-client")
form.Set("client_secret", "my-secret")
resp, _ := http.PostForm("https://auth.fd.agenticstar.tm.softbank.jp/federation/auth/v1/token", form)
defer resp.Body.Close()

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

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

| フィールド                | 型        | 説明                             |
| -------------------- | -------- | ------------------------------ |
| `access_token`       | `string` | JWT 形式のアクセストークン                |
| `id_token`           | `string` | JWT 形式の ID Token               |
| `expires_in`         | `number` | アクセストークンの有効期限（秒）               |
| `refresh_expires_in` | `number` | リフレッシュトークンの有効期限（秒）。AC フローのみ    |
| `refresh_token`      | `string` | リフレッシュトークン（トークン更新に使用）。AC フローのみ |
| `token_type`         | `string` | `"Bearer"`                     |
| `scope`              | `string` | 付与されたスコープ（スペース区切り）             |

### レスポンス例（Authorization Code フロー）

```json
{
  "access_token": "eyJhbGciOiJSUzI1NiIs...",
  "id_token": "eyJhbGciOiJSUzI1NiIs...",
  "expires_in": 3600,
  "refresh_expires_in": 86400,
  "refresh_token": "eyJhbGciOiJIUzI1NiIs...",
  "token_type": "Bearer",
  "scope": "openid chat:exec chat:history chat:file"
}
```

### レスポンス例（Client Credentials フロー）

```json
{
  "access_token": "eyJhbGciOiJSUzI1NiIs...",
  "id_token": "eyJhbGciOiJSUzI1NiIs...",
  "expires_in": 3600,
  "token_type": "Bearer",
  "scope": "openid users:read logs:read"
}
```

> **Client Credentials フローのレスポンス**
>
> Client Credentials フローではリフレッシュトークンは発行されません。`refresh_token` および `refresh_expires_in` フィールドはレスポンスに含まれません。

### エラーレスポンス

| ステータス | code                      | 説明                                                                            |
| ----- | ------------------------- | ----------------------------------------------------------------------------- |
| 400   | `invalid_request`         | 必須パラメータが不足、または形式が不正                                                           |
| 400   | `invalid_grant`           | Authorization Code が無効、または有効期限切れ                                              |
| 400   | `invalid_scope`           | リクエストされたスコープが無効                                                               |
| 401   | `invalid_client`          | クライアント認証に失敗（ID / Secret が不正）                                                  |
| 401   | `unauthorized_client`     | クライアントの利用条件を満たさない（例: 利用者のテナントが無効化されている、またはクライアントが「非公開」状態で `developer` ロールが必要） |
| 413   | `invalid_request`         | 本文が大きすぎる、または項目が多すぎる                                                           |
| 415   | `invalid_request`         | 本文の文字コード、または Content-Encoding に対応していない                                        |
| 502   | `bad_gateway`             | 認証基盤との通信に失敗                                                                   |
| 503   | `temporarily_unavailable` | 利用者のテナントの状態を確かめられなかった。時間をおいて再試行する                                             |

## Refresh Token

### POST`/federation/auth/v1/token`

Refresh Token を使用してアクセストークンを更新します。`grant_type=refresh_token` を指定します。リフレッシュのたびにレスポンスには新しい `refresh_token` が含まれます。

### リクエストボディ

| パラメータ           | 型        | 必須 | 説明                                |
| --------------- | -------- | -- | --------------------------------- |
| `grant_type`    | `string` | 必須 | refresh\_token を指定                |
| `refresh_token` | `string` | 必須 | Token エンドポイントから取得した Refresh Token |
| `client_id`     | `string` | 必須 | クライアントID                          |
| `client_secret` | `string` | 必須 | クライアントシークレット                      |

### リクエスト例

**Refresh token**

**curl**

```curl
curl -X POST https://auth.fd.agenticstar.tm.softbank.jp/federation/auth/v1/token \
-d "grant_type=refresh_token" \
-d "refresh_token=REFRESH_TOKEN" \
-d "client_id=my-client" \
-d "client_secret=my-secret"
```

**Python**

```python
import requests

response = requests.post(
  "https://auth.fd.agenticstar.tm.softbank.jp/federation/auth/v1/token",
  data={"grant_type": "refresh_token", "refresh_token": "REFRESH_TOKEN", "client_id": "my-client", "client_secret": "my-secret"},
)

print(response.json())
```

**TypeScript**

```typescript
const response = await fetch("https://auth.fd.agenticstar.tm.softbank.jp/federation/auth/v1/token", {
method: "POST",
body: new URLSearchParams({ grant_type: "refresh_token", refresh_token: "REFRESH_TOKEN", client_id: "my-client", client_secret: "my-secret" }),
});
const data = await response.json();
console.log(data);
```

**Go**

```go
form := url.Values{}
form.Set("grant_type", "refresh_token")
form.Set("refresh_token", "REFRESH_TOKEN")
form.Set("client_id", "my-client")
form.Set("client_secret", "my-secret")
resp, _ := http.PostForm("https://auth.fd.agenticstar.tm.softbank.jp/federation/auth/v1/token", form)
defer resp.Body.Close()

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

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

Token エンドポイントと同じ構造のレスポンスが返されます。[Token エンドポイント — レスポンスフィールド](#token-endpoint)を参照してください。

### レスポンス例

```json
{
  "access_token": "eyJhbGciOiJSUzI1NiIs...",
  "id_token": "eyJhbGciOiJSUzI1NiIs...",
  "expires_in": 3600,
  "refresh_expires_in": 86400,
  "refresh_token": "eyJhbGciOiJIUzI1NiIs...",
  "token_type": "Bearer",
  "scope": "openid chat:exec chat:history chat:file"
}
```

### エラーレスポンス

| ステータス | code                      | 説明                                      |
| ----- | ------------------------- | --------------------------------------- |
| 400   | `invalid_request`         | 必須パラメータが不足、または形式が不正                     |
| 400   | `invalid_grant`           | Refresh Token が無効、または有効期限切れ             |
| 401   | `invalid_client`          | クライアント認証に失敗（ID / Secret が不正）            |
| 401   | `unauthorized_client`     | クライアントの利用条件を満たさない（例: 利用者のテナントが無効化されている） |
| 413   | `invalid_request`         | 本文が大きすぎる、または項目が多すぎる                     |
| 415   | `invalid_request`         | 本文の文字コード、または Content-Encoding に対応していない  |
| 502   | `bad_gateway`             | 認証基盤との通信に失敗                             |
| 503   | `temporarily_unavailable` | 利用者のテナントの状態を確かめられなかった。時間をおいて再試行する       |

## UserInfo

### GET`/federation/auth/v1/userinfo`

有効なアクセストークンを使用してユーザー情報を取得します。テナント経由の認証の場合、OIDC 標準クレームに加えて `idp` ブロックに IdP のユーザー情報が含まれます。

OIDC Core 1.0 §5.3 に準拠し、`GET` と `POST` のどちらでも同一のレスポンスを返します。`POST` を使う場合も `Authorization: Bearer <access_token>` ヘッダーで認証してください。

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

| ヘッダー            | 必須 | 説明                      |
| --------------- | -- | ----------------------- |
| `Authorization` | 必須 | Bearer \<access\_token> |

### リクエスト例

**Get user info**

**curl**

```curl
curl https://auth.fd.agenticstar.tm.softbank.jp/federation/auth/v1/userinfo \
-H "Authorization: Bearer <access_token>"
```

**Python**

```python
import requests

response = requests.get(
  "https://auth.fd.agenticstar.tm.softbank.jp/federation/auth/v1/userinfo",
  headers={"Authorization": "Bearer <access_token>"},
)

print(response.json())
```

**TypeScript**

```typescript
const response = await fetch("https://auth.fd.agenticstar.tm.softbank.jp/federation/auth/v1/userinfo", {
headers: { "Authorization": "Bearer <access_token>" },
});
const data = await response.json();
console.log(data);
```

**Go**

```go
req, _ := http.NewRequest("GET", "https://auth.fd.agenticstar.tm.softbank.jp/federation/auth/v1/userinfo", nil)
req.Header.Set("Authorization", "Bearer <access_token>")
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）

| フィールド                    | 型         | 説明                            |
| ------------------------ | --------- | ----------------------------- |
| `sub`                    | `string`  | ユーザー ID（OIDC 標準）              |
| `idp`                    | `object`  | IdP から取得したユーザー情報（テナント経由の場合のみ） |
| `idp.sub`                | `string`  | IdP 側のユーザー ID                 |
| `idp.name`               | `string`  | ユーザー名                         |
| `idp.preferred_username` | `string`  | ユーザー名（メールアドレス）                |
| `idp.email`              | `string`  | メールアドレス                       |
| `idp.email_verified`     | `boolean` | メールアドレスが検証済みか                 |
| `idp.organization`       | `object`  | 所属組織（id と label を含む）          |
| `idp.job`                | `object`  | 役職（id と label を含む）            |
| `idp.bio`                | `string`  | 自己紹介                          |

### レスポンス例

```json
{
  "sub": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
  "idp": {
    "sub": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
    "name": "yamada_taro",
    "preferred_username": "taro.yamada@example.com",
    "email": "taro.yamada@example.com",
    "email_verified": true,
    "organization": {
      "id": "org-001",
      "label": "Example Corp."
    },
    "job": {
      "id": "job-001",
      "label": "Engineer"
    },
    "bio": "Software engineer"
  }
}
```

### エラーレスポンス

| ステータス | code                      | 説明                                                    |
| ----- | ------------------------- | ----------------------------------------------------- |
| 401   | `invalid_token`           | トークンが無効または有効期限切れ                                      |
| 413   | `invalid_request`         | 本文が大きすぎる、または項目が多すぎる                                   |
| 415   | `invalid_request`         | 本文の文字コード、または Content-Encoding に対応していない                |
| 429   | `temporarily_unavailable` | IdP 側のリクエスト数の上限を超えた。Retry-After ヘッダーがあれば、その時間の後に再試行する |
| 500   | `server_error`            | 認証基盤または IdP の設定エラー                                    |
| 502   | `bad_gateway`             | IdP からのユーザー情報取得に失敗                                    |

## JWKS

### GET`/federation/auth/v1/jwks`

JWT 署名検証用の公開鍵セット（JWKS）を取得します。ID Token や Access Token の署名検証に使用してください。

### リクエスト例

**Get JWKS**

**curl**

```curl
curl https://auth.fd.agenticstar.tm.softbank.jp/federation/auth/v1/jwks
```

**Python**

```python
import requests

response = requests.get(
  "https://auth.fd.agenticstar.tm.softbank.jp/federation/auth/v1/jwks",
)

print(response.json())
```

**TypeScript**

```typescript
const response = await fetch("https://auth.fd.agenticstar.tm.softbank.jp/federation/auth/v1/jwks");
const data = await response.json();
console.log(data);
```

**Go**

```go
req, _ := http.NewRequest("GET", "https://auth.fd.agenticstar.tm.softbank.jp/federation/auth/v1/jwks", 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[].kty` | `string` | 鍵タイプ（例: "RSA"）                      |
| `keys[].kid` | `string` | 鍵 ID。JWT ヘッダーの kid と照合して検証に使用する鍵を特定 |
| `keys[].use` | `string` | 鍵の用途。"sig"（署名検証）                    |
| `keys[].alg` | `string` | アルゴリズム（例: "RS256"）                  |
| `keys[].n`   | `string` | RSA 公開鍵のモジュラス（Base64url エンコード）      |
| `keys[].e`   | `string` | RSA 公開鍵の指数（Base64url エンコード）         |

### レスポンス例

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

### エラーレスポンス

| ステータス | code          | 説明               |
| ----- | ------------- | ---------------- |
| 502   | `bad_gateway` | 認証基盤からの公開鍵の取得に失敗 |

## Revoke

### POST`/federation/auth/v1/revoke`

アクセストークンや Refresh Token を失効させます。

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

| ヘッダー           | 必須 | 説明                                |
| -------------- | -- | --------------------------------- |
| `Content-Type` | 必須 | application/x-www-form-urlencoded |

### リクエストボディ

| パラメータ           | 型        | 必須 | 説明                                        |
| --------------- | -------- | -- | ----------------------------------------- |
| `token`         | `string` | 必須 | 失効させるトークン（Access Token または Refresh Token） |
| `client_id`     | `string` | 必須 | クライアントID                                  |
| `client_secret` | `string` | 必須 | クライアントシークレット                              |

### リクエスト例

**Revoke token**

**curl**

```curl
curl -X POST https://auth.fd.agenticstar.tm.softbank.jp/federation/auth/v1/revoke \
-d "token=ACCESS_TOKEN" \
-d "client_id=my-client" \
-d "client_secret=my-secret"
```

**Python**

```python
import requests

response = requests.post(
  "https://auth.fd.agenticstar.tm.softbank.jp/federation/auth/v1/revoke",
  data={"token": "ACCESS_TOKEN", "client_id": "my-client", "client_secret": "my-secret"},
)

print(response.status_code)
```

**TypeScript**

```typescript
const response = await fetch("https://auth.fd.agenticstar.tm.softbank.jp/federation/auth/v1/revoke", {
method: "POST",
body: new URLSearchParams({ token: "ACCESS_TOKEN", client_id: "my-client", client_secret: "my-secret" }),
});
console.log(response.status);
```

**Go**

```go
form := url.Values{}
form.Set("token", "ACCESS_TOKEN")
form.Set("client_id", "my-client")
form.Set("client_secret", "my-secret")
resp, _ := http.PostForm("https://auth.fd.agenticstar.tm.softbank.jp/federation/auth/v1/revoke", form)
defer resp.Body.Close()
fmt.Println(resp.StatusCode)
```

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

成功時は 200 OK（空のレスポンスボディ）が返されます。トークンが既に無効であっても 200 OK が返されます（RFC 7009 準拠）。

### エラーレスポンス

| ステータス | code              | 説明                                     |
| ----- | ----------------- | -------------------------------------- |
| 400   | `invalid_request` | 必須パラメータが不足、または形式が不正                    |
| 401   | `invalid_client`  | クライアント認証に失敗（ID / Secret が不正）           |
| 413   | `invalid_request` | 本文が大きすぎる、または項目が多すぎる                    |
| 415   | `invalid_request` | 本文の文字コード、または Content-Encoding に対応していない |
| 502   | `bad_gateway`     | 認証基盤との通信に失敗                            |

## JWT 仕様

ID Token および Access Token は JWT 形式で発行されます。JWT は署名済み（署名アルゴリズム: RS256）で、header.payload.signature の3部から構成されています。

### JWT 構造

```text
eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyLWlk....signature_part
```

### Header

```json
{
  "alg": "RS256",
  "typ": "JWT",
  "kid": "key-id-1"
}
```

### Payload（クレーム）

以下のセクションで詳細なクレーム一覧を参照してください。

## クレーム一覧

### 標準クレーム

AC（Authorization Code）フローと CC（Client Credentials）フローの両方に含まれるクレームです。

| クレーム                 | 型        | 説明                                                                            |
| -------------------- | -------- | ----------------------------------------------------------------------------- |
| `sub`                | `string` | サブジェクト ID。認証基盤内でユーザーまたはサービスアカウントを一意に識別する UUID                                 |
| `iss`                | `string` | Issuer。トークン発行元（https\://auth.fd.agenticstar.tm.softbank.jp/realms/federation） |
| `exp`                | `number` | 有効期限（Unix タイムスタンプ）                                                            |
| `iat`                | `number` | 発行日時（Unix タイムスタンプ）                                                            |
| `jti`                | `string` | JWT ID。トークンを一意に識別する ID                                                        |
| `typ`                | `string` | トークン種別（"Bearer"）                                                              |
| `azp`                | `string` | Authorized Party。トークンを要求したクライアント ID                                           |
| `scope`              | `string` | 付与されたスコープ（スペース区切り）                                                            |
| `preferred_username` | `string` | ユーザー名（CC フローのみ、`service-account-<client-id>@federation.invalid` 形式）           |

### AC フロー固有クレーム

Authorization Code フローで発行されたトークンにのみ含まれるクレームです。

| クレーム              | 型          | 説明                                    |
| ----------------- | ---------- | ------------------------------------- |
| `aud`             | `string`   | Audience。固定値 `"broker"`（認証基盤内部の対象識別子） |
| `sid`             | `string`   | Session ID。認証セッションの識別子                |
| `auth_time`       | `number`   | ユーザー認証が完了した日時（Unix タイムスタンプ）           |
| `allowed-origins` | `string[]` | 許可された Origin（CORS 用途）                 |

### テナント情報（`tenant.*`）

テナント（企業 / SaaS）に関する情報です。AC / CC の両方で、Access Token および ID Token にネスト構造で含まれます。

| クレーム              | 型        | 説明                  | トークン     |
| ----------------- | -------- | ------------------- | -------- |
| `tenant.id`       | `string` | テナント ID             | AT / IDT |
| `tenant.type`     | `string` | enterprise または saas | AT / IDT |
| `tenant.endpoint` | `string` | テナントのエンドポイント URL    | AT / IDT |

### IdP プロフィール（`idp.*`）

IdP（企業認証基盤）から取得したユーザー情報です。AC フローではログインしたユーザーの情報がネスト構造で含まれます。CC フローでは `idp.*` は含まれません。

| クレーム                     | 型        | 説明                 | トークン     |
| ------------------------ | -------- | ------------------ | -------- |
| `idp.sub`                | `string` | IdP ユーザー ID        | AT / IDT |
| `idp.preferred_username` | `string` | IdP ユーザー名（メールアドレス） | AT / IDT |
| `idp.display_name`       | `string` | 表示名                | IDT      |
| `idp.email`              | `string` | メールアドレス            | IDT      |
| `idp.organization`       | `string` | 所属組織               | AT / IDT |
| `idp.job`                | `string` | 役職                 | AT / IDT |
| `idp.bio`                | `string` | 自己紹介               | AT / IDT |

### ロール

| クレーム                             | 型          | 説明                                                                         |
| -------------------------------- | ---------- | -------------------------------------------------------------------------- |
| `realm_access.roles`             | `string[]` | Realm ロール。AC ではユーザーに付与されたロール（例: user, admin, developer）、CC では `["M2M"]` 固定 |
| `resource_access.<client>.roles` | `string[]` | クライアント固有ロール（AC フローのみ付与される場合あり）                                             |

### Access Token Payload 例（Authorization Code フロー）

```json
{
  "exp": 1745049600,
  "iat": 1745048100,
  "jti": "onrtac:abc12345-6789-4def-8abc-0123456789ab",
  "iss": "https://auth.fd.agenticstar.tm.softbank.jp/realms/federation",
  "aud": "broker",
  "sub": "11111111-2222-3333-4444-555555555555",
  "typ": "Bearer",
  "azp": "my-client",
  "sid": "99999999-8888-7777-6666-555555555555",
  "allowed-origins": ["http://localhost:4000"],
  "realm_access": {
    "roles": ["admin", "developer", "user"]
  },
  "resource_access": {
    "broker": { "roles": ["read-token"] }
  },
  "scope": "openid mcp:all chat:file chat:history email a2a:all profile chat:exec",
  "auth_time": 1745048090,
  "tenant": {
    "id": "enterprise-a",
    "type": "enterprise",
    "endpoint": "https://enterprise-a.example.com"
  },
  "idp": {
    "sub": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
    "organization": "Enterprise A Division",
    "bio": "Software developer",
    "preferred_username": "user@enterprise-a.com",
    "job": "Engineer"
  }
}
```

### Access Token Payload 例（Client Credentials フロー）

```json
{
  "exp": 1745049600,
  "iat": 1745048100,
  "jti": "trrtcc:abc12345-6789-4def-8abc-0123456789ab",
  "iss": "https://auth.fd.agenticstar.tm.softbank.jp/realms/federation",
  "sub": "22222222-3333-4444-5555-666666666666",
  "typ": "Bearer",
  "azp": "my-cc-client",
  "realm_access": {
    "roles": ["M2M"]
  },
  "scope": "openid sharedmemory:query users:manage master:manage logs:read users:read",
  "preferred_username": "service-account-my-cc-client@federation.invalid",
  "tenant": {
    "id": "enterprise-a",
    "type": "enterprise",
    "endpoint": "https://enterprise-a.example.com"
  }
}
```

> **注記**
>
> - AC フローは `aud`（`"broker"` 固定）、`sid`、`auth_time`、`allowed-origins` を含みますが、CC フローには含まれません。
> - AC フローの `realm_access.roles` は Console で割り当てたユーザーロール、CC フローは `"M2M"` 固定です。

## スコープ

### スコープ一覧

| スコープ                 | 説明                                                                                                                                                                        |
| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `chat:exec`          | チャットの開始・停止、ストリーミング応答の受信、成果物の取得                                                                                                                                            |
| `chat:history`       | 会話一覧・メッセージ履歴の取得（アクティブ / アーカイブ）、会話の削除・タイトル更新・アーカイブ済み会話の復元、メッセージ検索                                                                                                          |
| `chat:file`          | チャットで使用するファイルのアップロード・取得・削除                                                                                                                                                |
| `mcp:connect`        | MCP（Model Context Protocol）に接続（使えるツールは、あわせて持つスコープで決まる）                                                                                                                    |
| `mcp:all`            | MCP のすべてのツールを使う                                                                                                                                                           |
| `a2a:connect`        | A2A（Agent-to-Agent）プロトコルに接続（使える操作は、あわせて持つスコープで決まる）                                                                                                                        |
| `a2a:all`            | A2A のすべての操作を使う                                                                                                                                                            |
| `sharedmemory:query` | 共有メモリの検索                                                                                                                                                                  |
| `users:read`         | ユーザー情報の読み取り（一覧・詳細）                                                                                                                                                        |
| `users:manage`       | ユーザーの管理操作（作成・承認・承認取り消し・削除・ロール変更・利用の停止と再開・ロックの解除・所属と職種の変更）。読み取り権限を含む                                                                                                       |
| `logs:read`          | ログの閲覧（監査ログ・操作監査ログ・利用者の操作の監査・LLMログ・LLM Gateway ログ・LLM Gateway 操作監査・アクセスログ・ガードレールアラート）                                                                                      |
| `master:manage`      | マスターデータの管理（組織・職種の作成・更新・削除）                                                                                                                                                |
| `project:read`       | プロジェクトの参照（アプリケーションでは参加しているプロジェクトと、組織の運用の役割で読めるプロジェクトの、実行・記録・確認依頼・キュー・プロジェクトのライブラリの閲覧（組織の運用の役割では、プロジェクトのライブラリと確認依頼は読めません。確認依頼は、キューの行には出ます）、システム連携ではプロジェクト制限の範囲の一覧と実行状況の参照） |
| `project:run`        | プロジェクトの実行開始・トリガーの発火・ワークフローの実行の中断（アプリケーションでは失敗した巡回の再実行と、閉じたワークフローの実行の再開も）                                                                                                  |
| `project:write`      | プロジェクトの作成と、オーナーのプロジェクトの変更（ワークフローの実行の締め切りと確認担当者の付け替え、プロジェクトの一時停止と再開は、運用担当として参加しているプロジェクトと、組織の運用の役割を持つ組織のプロジェクトでも）、プロジェクトのライブラリのファイルの登録・変更・削除（アプリケーションだけ）                   |
| `project:delete`     | オーナーのプロジェクトの削除（アプリケーションだけ）                                                                                                                                                |
| `project:decide`     | 担当の確認依頼（期間中の代理人として決められる確認依頼を含む）の判断と、確認依頼の期限の延長（期限の延長は、オーナー・運用担当と組織の運用の役割の人もできます。アプリケーションだけ）                                                                               |
| `assets:read`        | Agent・Playbook・Skill の閲覧（アプリケーションだけ）                                                                                                                                      |
| `assets:write`       | Agent・Playbook・Skill の作成・変更・コピー（アプリケーションだけ）                                                                                                                               |
| `assets:delete`      | Agent・Playbook・Skill の削除（アプリケーションだけ）                                                                                                                                      |

各スコープの詳細や選択の指針については、[認証ガイド — スコープ](https://developers.fd.agenticstar.tm.softbank.jp/docs/saas/api/agent/guide/auth-guide.md#%E3%82%B9%E3%82%B3%E3%83%BC%E3%83%97)を参照してください。

### スコープ制御の仕組み

Console でクライアントにスコープを割り当てることで、トークンに含まれるスコープが決定されます。ユーザーのロールで許可されたスコープのみがトークンに付与されます。

## エラーコード

### OAuth 2.0 / OIDC エラー

| エラーコード                    | 説明                                         | 対応方法                                     |
| ------------------------- | ------------------------------------------ | ---------------------------------------- |
| `invalid_request`         | 必須パラメータが不足、または形式が不正                        | リクエストパラメータを確認してください                      |
| `unauthorized_client`     | クライアントに権限がない、またはクライアント ID が不正              | クライアント ID と設定を確認してください                   |
| `invalid_client`          | クライアント認証に失敗（ID / Secret が不正）               | クライアント ID とシークレットを確認してください               |
| `invalid_grant`           | Authorization Code が無効、有効期限切れ、または既に使用済み    | Authorization Code を再取得してください            |
| `invalid_scope`           | リクエストされたスコープが無効、または未割り当て                   | Console でクライアントにスコープを割り当ててください           |
| `server_error`            | 認証基盤との通信エラーなど、サーバー側のエラー                    | しばらく待ってから再度お試しください。問題が続く場合はサポートに連絡してください |
| `invalid_token`           | トークンが無効または有効期限切れ                           | 新しいトークンを取得してください                         |
| `temporarily_unavailable` | IdP 側のリクエスト数の上限を超えた（UserInfo エンドポイントの 429） | Retry-After ヘッダーがあれば、その時間の後に再試行してください    |

### HTTP ステータスコード

| ステータス                        | 説明                                     |
| ---------------------------- | -------------------------------------- |
| `200 OK`                     | リクエストが成功                               |
| `302 Found`                  | リダイレクト（Authorization エンドポイント）          |
| `400 Bad Request`            | リクエストが不正                               |
| `401 Unauthorized`           | 認証に失敗、またはトークンが無効                       |
| `403 Forbidden`              | リクエストが禁止されている                          |
| `413 Payload Too Large`      | 本文が大きすぎる、または項目が多すぎる                    |
| `415 Unsupported Media Type` | 本文の文字コード、または Content-Encoding に対応していない |
| `429 Too Many Requests`      | IdP 側のリクエスト数の上限を超えた（UserInfo エンドポイント）  |
| `500 Internal Server Error`  | サーバー内部エラー                              |
| `502 Bad Gateway`            | 認証基盤との通信に失敗                            |
