# 🛡️ IDaaS と BFF (Identity Platform・Cognito・Auth0)
IDaaS (Identity as a Service) は、利用者の台帳と、Google・GitHub などの IdP でのログインを引き受けるサービスです。アプリは IdP ごとの違いを知らずに、IDaaS が発行したトークンで利用者を見分けられます。

ここでは、Identity Platform・Cognito・Auth0 の 3 つで、BFF (Next.js のサーバー) がログインしてから API を呼ぶまでの流れを比べます。OAuth と OIDC の基本は [OAuth の資料](../OAuth/README.md) を先に読んでください。

前提:
- BFF は、client_secret などの秘密を持てる機密クライアントです ([OAuth の資料](../OAuth/README.md) の表)
- トークンは BFF だけが持ちます。BFF のセッションストア (Valkey など) にトークンを置き、ブラウザの Cookie には推測できないセッション ID だけを入れます。ブラウザの JS からも、Cookie を盗み見た人からも、トークンは見えません
- このアプリは Identity Platform を使っています。実装は [identity の README](https://github.com/theindiehacker/app.fastship.jp/blob/main/frontend/src/features/identity/README.md) にあります

## 🧭 3 つの違い

いちばん大きな違いは、**IdP (Google) でログインした後に、どこへ戻るか**です。

- Identity Platform: IdP から**アプリのコールバック**に戻ります。BFF は、戻ってきた URL を Identity Platform に渡すだけです
- Cognito・Auth0: IdP から **IDaaS のドメイン**に戻ります。IDaaS が自分の認可コードを付けてアプリに戻すので、BFF は IDaaS を相手に、ふつうの OIDC の認可コードフローを行います

| | 🔥 Identity Platform | 🟠 Cognito | 🔴 Auth0 |
| :-- | :-- | :-- | :-- |
| IdP から戻る先 | アプリのコールバック (IdP ごと) | Cognito の `/oauth2/idpresponse` | Auth0 の `/login/callback` |
| IdP の選び方 | `createAuthUri` の `providerId` | 認可リクエストの `identity_provider` | 認可リクエストの `connection` |
| BFF が作る値 | 無し (Identity Platform が返した sessionId を覚えるだけ) | 🎲 state・🧷 nonce・🧩 code_verifier | 🎲 state・🧷 nonce・🧩 code_verifier |
| BFF がすること | REST の API を 2 つ呼ぶ | トークンの交換と ID トークンの検証 (OIDC のクライアント) | トークンの交換と ID トークンの検証 (OIDC のクライアント) |
| BFF が持つ秘密 | API キー | アプリクライアントの client_secret | アプリケーションの client_secret |
| IdP (Google) の client_secret の置き場所 | Identity Platform | Cognito | Auth0 |
| API に渡すトークン | Identity Platform の ID トークン | Cognito のアクセストークン | Auth0 のアクセストークン |
| API が宛先を確かめる値 | `aud` (プロジェクト ID) | `client_id`・`token_use` (アクセストークンに `aud` が無い) | `aud` (API の識別子) |
| トークンの更新 | `securetoken.googleapis.com` | Cognito の `/oauth2/token` | Auth0 の `/oauth/token` (`offline_access` のスコープが要る) |
| Next.js 向けの SDK | 無し (REST を呼ぶ) | 無し (openid-client などの OIDC ライブラリ) | `@auth0/nextjs-auth0` |

---
## 🔥 Identity Platform

BFF は、IdP のログイン画面の URL を Identity Platform に作らせ (`createAuthUri`)、IdP から戻ってきた URL を Identity Platform に渡します (`signInWithIdp`)。state の照合・認可コードの交換・IdP の ID トークンの検証は、すべて Identity Platform が行います。

```mermaid
sequenceDiagram
    actor User as 🥸 利用者 (ブラウザ)
    participant BFF as 🖥️ BFF (Next.js のサーバー)
    participant Store as 🗄️ セッションストア
    participant IP as 🔥 Identity Platform
    participant IdP as 🔑 IdP (Google)
    participant API as 🚀 API

    rect rgb(150, 150, 150)
        Note over User,IP: 1. ログインを始める
        User->>BFF: GET /oauth/google
        BFF->>IP: accounts:createAuthUri<br/>(providerId=google.com・continueUri=アプリのコールバック・CODE_FLOW)
        IP->>IP: 🎲 state を作り、sessionId と結び付けて覚える
        IP-->>BFF: authUri (IdP の認可エンドポイントの URL)・sessionId
        BFF-->>User: 302 authUri<br/>Cookie: sessionId (暗号化。10 分)
    end

    rect rgb(150, 150, 150)
        Note over User,IdP: 2. IdP でログインする
        User->>IdP: ログイン・同意
        IdP-->>User: 302 アプリのコールバック?code=🎫&state=🎲
    end

    rect rgb(150, 100, 100)
        Note over User,IdP: 3. トークンを受け取る
        User->>BFF: GET /oauth/google/callback?code=🎫&state=🎲<br/>Cookie: sessionId
        BFF->>IP: accounts:signInWithIdp<br/>(requestUri=コールバックの URL とクエリ・sessionId)
        IP->>IP: 🎲 state を sessionId と照合する
        IP->>IdP: 🎫 認可コードをトークンに交換する<br/>(Identity Platform に設定した Google の client_secret)
        IdP-->>IP: Google の ID トークンなど
        IP->>IP: Google の ID トークンを確かめ、利用者を探す (初めてなら登録する)
        IP-->>BFF: 🆔 Identity Platform の ID トークン (1 時間)・🔄 リフレッシュトークン
        BFF->>Store: トークンと利用者を保存する
        BFF-->>User: 302 ログインを始めた画面<br/>Cookie: セッション ID だけ
    end

    rect rgb(100, 120, 150)
        Note over User,API: 4. API を呼ぶ
        User->>BFF: 画面の操作<br/>Cookie: セッション ID
        BFF->>Store: トークンを読む
        BFF->>API: Authorization: Bearer 🆔 Identity Platform の ID トークン
        API->>API: 署名 (securetoken の公開鍵)・iss・aud (プロジェクト ID)・exp を確かめる
        API-->>BFF: 結果
        BFF-->>User: 画面 (トークンは入れない)
    end

    rect rgb(100, 150, 100)
        Note over BFF,IP: 5. トークンを更新する (期限の前に)
        BFF->>IP: POST securetoken.googleapis.com/v1/token<br/>(grant_type=refresh_token・🔄 リフレッシュトークン)
        IP-->>BFF: 新しい 🆔 ID トークン・🔄 リフレッシュトークン<br/>(アカウントが無効なら失敗する)
        BFF->>Store: 入れ替える
    end
```

- IdP ごとに、アプリのコールバックの URL を IdP に登録します (Google の OAuth クライアントのリダイレクト URI など)
- BFF は IdP と直接話しません。IdP の client_secret も Identity Platform に置くので、BFF が持つ秘密は API キーだけです

---
## 🟠 Cognito

BFF は Cognito の OIDC のクライアントになります。Cognito の認可エンドポイントに `identity_provider=Google` を付けて送ると、Cognito が Google とのやり取りを済ませ、Cognito の認可コードを付けてアプリに戻します。

```mermaid
sequenceDiagram
    actor User as 🥸 利用者 (ブラウザ)
    participant BFF as 🖥️ BFF (Next.js のサーバー)
    participant Store as 🗄️ セッションストア
    participant Cognito as 🟠 Cognito (User Pool)
    participant IdP as 🔑 IdP (Google)
    participant API as 🚀 API

    rect rgb(150, 150, 150)
        Note over User,Cognito: 1. ログインを始める
        User->>BFF: GET /oauth/google
        BFF->>BFF: 🎲 state・🧷 nonce・🧩 code_verifier を作る
        BFF-->>User: 302 https://<Cognito のドメイン>/oauth2/authorize<br/>?response_type=code&client_id=<🪪>&redirect_uri=アプリのコールバック<br/>&identity_provider=Google&scope=openid email profile<br/>&state=🎲&nonce=🧷&code_challenge=🧩<br/>Cookie: state・nonce・code_verifier (暗号化。10 分)
    end

    rect rgb(150, 150, 150)
        Note over User,IdP: 2. IdP でログインする (Cognito が仲立ちする)
        User->>Cognito: GET /oauth2/authorize?...
        Cognito-->>User: 302 Google の認可エンドポイント<br/>(redirect_uri=Cognito の /oauth2/idpresponse)
        User->>IdP: ログイン・同意
        IdP-->>User: 302 Cognito の /oauth2/idpresponse?code=🎫 (Google の)
        User->>Cognito: GET /oauth2/idpresponse?code=🎫
        Cognito->>IdP: Google の認可コードをトークンに交換する<br/>(Cognito に設定した Google の client_secret)
        IdP-->>Cognito: Google の ID トークンなど
        Cognito->>Cognito: Google の ID トークンを確かめ、利用者を探す (初めてなら登録する)
        Cognito-->>User: 302 アプリのコールバック?code=🎫 (Cognito の)&state=🎲
    end

    rect rgb(150, 100, 100)
        Note over User,Cognito: 3. トークンを受け取る
        User->>BFF: GET /oauth/google/callback?code=🎫&state=🎲<br/>Cookie: state・nonce・code_verifier
        BFF->>BFF: 🎲 state が覚えた値と同じか確かめる
        BFF->>Cognito: POST /oauth2/token<br/>(code=🎫・code_verifier=🧩・client_id と client_secret)
        Cognito-->>BFF: 🆔 ID トークン・🔑 アクセストークン・🔄 リフレッシュトークン
        BFF->>BFF: ID トークンの署名 (User Pool の公開鍵)・iss・aud・exp・🧷 nonce を確かめる
        BFF->>Store: トークンと利用者を保存する
        BFF-->>User: 302 ログインを始めた画面<br/>Cookie: セッション ID だけ
    end

    rect rgb(100, 120, 150)
        Note over User,API: 4. API を呼ぶ
        User->>BFF: 画面の操作<br/>Cookie: セッション ID
        BFF->>Store: トークンを読む
        BFF->>API: Authorization: Bearer 🔑 Cognito のアクセストークン
        API->>API: 署名 (User Pool の公開鍵)・iss・client_id・token_use=access・exp を確かめる
        API-->>BFF: 結果
        BFF-->>User: 画面 (トークンは入れない)
    end

    rect rgb(100, 150, 100)
        Note over BFF,Cognito: 5. トークンを更新する (期限の前に)
        BFF->>Cognito: POST /oauth2/token<br/>(grant_type=refresh_token・🔄 リフレッシュトークン・client_secret)
        Cognito-->>BFF: 新しい 🆔 ID トークン・🔑 アクセストークン
        BFF->>Store: 入れ替える
    end
```

- IdP に登録するリダイレクト URI は、Cognito の `/oauth2/idpresponse` 1 つです。アプリのコールバックの URL は、Cognito のアプリクライアントに登録します
- Cognito のアクセストークンには `aud` がありません。API は `client_id` と `token_use` で、自分宛てかを確かめます

---
## 🔴 Auth0

流れは Cognito とほぼ同じで、BFF は Auth0 の OIDC のクライアントになります。違いは、IdP を `connection` で選ぶことと、`audience` に API の識別子を渡すと、アクセストークンがその API 宛ての JWT になることです。

```mermaid
sequenceDiagram
    actor User as 🥸 利用者 (ブラウザ)
    participant BFF as 🖥️ BFF (Next.js のサーバー)
    participant Store as 🗄️ セッションストア
    participant Auth0 as 🔴 Auth0
    participant IdP as 🔑 IdP (Google)
    participant API as 🚀 API

    rect rgb(150, 150, 150)
        Note over User,Auth0: 1. ログインを始める
        User->>BFF: GET /oauth/google
        BFF->>BFF: 🎲 state・🧷 nonce・🧩 code_verifier を作る
        BFF-->>User: 302 https://<テナント>.auth0.com/authorize<br/>?response_type=code&client_id=<🪪>&redirect_uri=アプリのコールバック<br/>&connection=google-oauth2&audience=<API の識別子><br/>&scope=openid email profile offline_access<br/>&state=🎲&nonce=🧷&code_challenge=🧩<br/>Cookie: state・nonce・code_verifier (暗号化。10 分)
    end

    rect rgb(150, 150, 150)
        Note over User,IdP: 2. IdP でログインする (Auth0 が仲立ちする)
        User->>Auth0: GET /authorize?...
        Auth0-->>User: 302 Google の認可エンドポイント<br/>(redirect_uri=Auth0 の /login/callback)
        User->>IdP: ログイン・同意
        IdP-->>User: 302 Auth0 の /login/callback?code=🎫 (Google の)
        User->>Auth0: GET /login/callback?code=🎫
        Auth0->>IdP: Google の認可コードをトークンに交換する<br/>(Auth0 に設定した Google の client_secret)
        IdP-->>Auth0: Google の ID トークンなど
        Auth0->>Auth0: 利用者を探す (初めてなら登録する)
        Auth0-->>User: 302 アプリのコールバック?code=🎫 (Auth0 の)&state=🎲
    end

    rect rgb(150, 100, 100)
        Note over User,Auth0: 3. トークンを受け取る
        User->>BFF: GET /oauth/google/callback?code=🎫&state=🎲<br/>Cookie: state・nonce・code_verifier
        BFF->>BFF: 🎲 state が覚えた値と同じか確かめる
        BFF->>Auth0: POST /oauth/token<br/>(code=🎫・code_verifier=🧩・client_id と client_secret)
        Auth0-->>BFF: 🆔 ID トークン・🔑 アクセストークン (API 宛ての JWT)<br/>・🔄 リフレッシュトークン (offline_access のときだけ)
        BFF->>BFF: ID トークンの署名 (テナントの公開鍵)・iss・aud・exp・🧷 nonce を確かめる
        BFF->>Store: トークンと利用者を保存する
        BFF-->>User: 302 ログインを始めた画面<br/>Cookie: セッション ID だけ
    end

    rect rgb(100, 120, 150)
        Note over User,API: 4. API を呼ぶ
        User->>BFF: 画面の操作<br/>Cookie: セッション ID
        BFF->>Store: トークンを読む
        BFF->>API: Authorization: Bearer 🔑 Auth0 のアクセストークン
        API->>API: 署名 (テナントの公開鍵)・iss・aud (API の識別子)・exp・scope を確かめる
        API-->>BFF: 結果
        BFF-->>User: 画面 (トークンは入れない)
    end

    rect rgb(100, 150, 100)
        Note over BFF,Auth0: 5. トークンを更新する (期限の前に)
        BFF->>Auth0: POST /oauth/token<br/>(grant_type=refresh_token・🔄 リフレッシュトークン・client_secret)
        Auth0-->>BFF: 新しい 🔑 アクセストークン<br/>(ローテーションを有効にしていれば、新しい 🔄 リフレッシュトークンも)
        BFF->>Store: 入れ替える
    end
```

- IdP に登録するリダイレクト URI は、Auth0 の `/login/callback` 1 つです。アプリのコールバックの URL は、Auth0 のアプリケーションに登録します
- `@auth0/nextjs-auth0` は、1・3・5 とセッションの作成を引き受けます。既定では、セッション (トークンを含む) を暗号化した Cookie に入れます。トークンをブラウザに一切出さないなら、セッションストアを使う設定にします
