> ## Documentation Index
> Fetch the complete documentation index at: https://translations.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# エンタープライズ接続（IPSIE）のセッション有効期限を設定する

> Okta および OIDC エンタープライズ接続で、IPSIE の `session_expiry` クレームを使用して上流の ID プロバイダーのセッション有効期限を適用する方法を説明します。

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  セッション有効期限は Okta および OIDC エンタープライズ接続でサポートされていますが、Microsoft Entra ID (Azure AD) 接続では利用できません。Microsoft は Entra ID トークンに `session_expiry` クレームを含めていません。
</Callout>

Auth0 は、Okta および OIDC エンタープライズ接続向けに、[Interoperability Profile for Secure Identity in the Enterprise (IPSIE) 標準](https://openid.net/specs/ipsie-openid-connect-sl1-profile-1_0.html)に基づく `session_expiry` クレームをサポートしています。有効にすると、Auth0 は上流の ID プロバイダー (IdP) から `session_expiry` (Unix タイムスタンプを秒単位で表した値) を取得し、アプリケーションに発行する ID トークンに含めます。

Auth0 は `session_expiry` クレームを使用して、ローカルの Auth0 セッションを上流の IdP のセッションライフサイクルと同期します。これにより、ユーザーのセッションがエンタープライズ IdP で期限切れになると、Auth0 セッションも終了します。

<Warning>
  受信した `session_expiry` クレームを処理し、アプリケーション内のユーザーセッションを終了・管理する責任はお客様にあります。
</Warning>

<Card title="始める前に">
  セッション有効期限の適用を有効にする前に、以下を確認してください。

  * [Okta](/docs/ja-jp/authenticate/identity-providers/enterprise-identity-providers/okta/express-configuration) または [OIDC](/docs/ja-jp/authenticate/identity-providers/enterprise-identity-providers/oidc) のエンタープライズ接続がすでに存在している必要があります。
  * 上流のアイデンティティプロバイダーが、ID トークンに `session_expiry` クレームを含める必要があります。
</Card>

<div id="how-it-works">
  ## 仕組み
</div>

ユーザーが `session_expiry` が有効なエンタープライズ接続を通じて認証されると、Auth0 は次の処理を行います。

1. 上流 IdP の ID トークンから `session_expiry` クレームを取得します。
2. 特定のパラメータを評価してセッションの有効期限を計算し、最終的な Auth0 セッションの有効期限を、次の要素のうち最も早い値に設定します。
   * IdP の `session_expiry` クレーム: 上流 IDプロバイダーが発行する ID トークンに含まれる絶対タイムスタンプです。
   * Auth0 テナントのデフォルトの絶対有効期限設定: Auth0 Dashboard または Management API で設定するセッション有効期間の上限です。詳細については、[セッション有効期間設定を構成する](/docs/ja-jp/manage-users/sessions/configure-session-lifetime-settings)を参照してください。
   * Auth0 Actions の \[`setExpiresAt`]: Post-Login Action の [`api.session.setExpiresAt()`](/docs/ja-jp/customize/actions/explore-triggers/signup-and-login-triggers/login-trigger/post-login-api-object#api-session-setexpiresat-absolute) メソッドを使用して、ログイントランザクション中にプログラムで設定したカスタム有効期限タイムスタンプです。
3. 有効化時に構成する Post-Login Action を使用して、評価後の最終セッション有効期限を[カスタムクレーム](/docs/ja-jp/customize/actions/explore-triggers/signup-and-login-triggers/login-trigger/post-login-api-object#api-idtoken-setcustomclaim-key-value)として Auth0 発行の ID トークンに注入し、アプリケーションに渡します。

`session_expiry` クレームは、ユーザーセッションの絶対有効期限を表す秒単位の [UNIX タイムスタンプ](https://en.wikipedia.org/wiki/Unix_time)です。

```json theme={null}
{
  "iss": "https://YOUR_DOMAIN.auth0.com/",
  "aud": "YOUR_CLIENT_ID",
  "sub": "oidc|username@domain.com",
  "iat": 1748534400,
  "exp": 1748538000,
  "session_expiry": 1748566800
}
```

| クレーム             | 内容                    | スコープ         |
| ---------------- | --------------------- | ------------ |
| `exp`            | ID トークンの有効期間 (通常は分単位) | トークンのバリデーション |
| `session_expiry` | 絶対的な有効期限 (秒)          | セッション管理      |

`session_expiry` クレームは `exp` の代替ではありません。ID トークン自体の `exp` は引き続き短い有効期間のままで、変更されません。`session_expiry` は、トークンのクレームに含まれるセッションレベルの制限です。

**`session_expiry` はログイン時に固定されます。** ユーザーの認証時に一度だけ設定され、トークンを更新しても変更されません。この機能を有効にする前にログインしていたユーザーの既存セッションには、`session_expiry` は含まれません。このクレームは、次回ログインした後にのみ追加されます。

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  この機能は、予定されたセッション有効期限のみを対象としています。セッション中にユーザーが退職した場合など、リアルタイムでセッションを取り消すには、[バックチャネルログアウト](/docs/ja-jp/authenticate/login/logout/back-channel-logout) の使用をおすすめします。
</Callout>

<div id="enable-session-expiry-enforcement">
  ## セッション有効期限の強制を有効化する
</div>

Auth0 Dashboard または Management API を使用して、エンタープライズ接続のセッション有効期限の強制を設定します。

<Tabs>
  <Tab title="Auth0 Dashboard">
    1. Auth0 Dashboard で、[Auth0 Dashboard > Authentication > Enterprise](https://manage.auth0.com/#/connections/enterprise) に移動します。
    2. Okta または OpenID Connect のエンタープライズ接続を見つけ、**Browse** を選択します。
    3. 設定する接続を選択します。
    4. ［設定］で、**Use ID Token for Session Expiry** を有効にします。
    5. **Save** を選択します。
  </Tab>

  <Tab title="Management API">
    Management API を使用するには、`update:connections` スコープを持つ [Management API access token](/docs/ja-jp/secure/tokens/access-tokens/management-api-access-tokens) が必要です。

    [Update a connection](https://auth0.com/docs/api/management/v2/connections/patch-connections-by-id) エンドポイントに `PATCH` リクエストを送信します。

    ```http theme={null}
    PATCH https://YOUR_DOMAIN/api/v2/connections/YOUR_CONNECTION_ID
    Content-Type: application/json
    Authorization: Bearer YOUR_MANAGEMENT_API_TOKEN

    {
      "options": {
        "id_token_session_expiry_supported": true
      }
    }
    ```

    プレースホルダー値を置き換えます。

    * **`YOUR_DOMAIN`**: Auth0 テナントのドメイン。例: `travel0.us.auth0.com`。
    * **`YOUR_CONNECTION_ID`**: Okta または OIDC エンタープライズ接続の ID。
    * **`YOUR_MANAGEMENT_API_TOKEN`**: `update:connections` スコープを持つ Management API トークン。

    <Callout icon="file-lines" color="#0EA5E9" iconType="regular">
      `options` パラメータを `PATCH` すると、`options` オブジェクト全体が上書きされます。`options` を `PATCH` する際は、既存のすべてのプロパティを含めてください。
    </Callout>
  </Tab>
</Tabs>

<div id="send-session-expiration-to-your-application">
  ## セッションの有効期限をアプリケーションに送信する
</div>

Auth0 は算出したセッションの有効期限を使用して独自のセッションレイヤーを管理しますが、ダウンストリームアプリケーションでもローカルのセッション制限を適用するため、この絶対的な有効期限を把握する必要がある場合があります。Post-Login Action を設定して、最終的に確定したセッションの有効期限を Auth0 発行の ID トークンにカスタムクレームとして追加し、そのトークンをアプリケーションに渡します。

<Tabs>
  <Tab title="Auth0 Dashboard">
    1. Auth0 Dashboard で [**Auth0 Dashboard > Actions > Library**](https://manage.auth0.com/#/actions/library) に移動し、**Build Custom Action** を選択します。
    2. Action の名前を入力し、トリガーとして **Login / Post Login** を選択して、**Create** を選択します。
    3. Action に次のコードを追加します。

    ```javascript theme={null}
    exports.onExecutePostLogin = async (event, api) => {
      // セッションの有効期限が設定されているか確認する
      if (event.session?.expires_at) {
        // ISO 形式の日時文字列を Date オブジェクトに変換する
        const exp_date = new Date(event.session.expires_at);
        // session_expiry カスタムクレームを Unix タイムスタンプ（秒）として設定する
        api.idToken.setCustomClaim('session_expiry', Math.floor((exp_date.getTime()) / 1000));
      }
    };
    ```

    4. Test パネルで **Run** を選択し、結果を確認します。
    5. **Deploy** を選択します。
    6. [**Actions > Triggers**](https://manage.auth0.com/#/actions/triggers) に移動し、**Post-Login** を選択します。
    7. Action を見つけてログインフローにドラッグし、**Apply** を選択します。
  </Tab>

  <Tab title="Management API">
    Management API を使用した Action の設定は、Action の作成、デプロイ、Login トリガーへのバインドの 3 ステップで行います。`create:actions`、`read:actions`、`update:actions` のスコープを持つ [Management API access token](/docs/ja-jp/secure/tokens/access-tokens/management-api-access-tokens) が必要です。

    ### Action を作成する

    1. [Create an action](https://auth0.com/docs/api/management/v2/actions/post-action) エンドポイントに `POST` リクエストを送信します。

    ```http theme={null}
    POST https://YOUR_DOMAIN/api/v2/actions/actions
    Content-Type: application/json
    Authorization: Bearer YOUR_MANAGEMENT_API_TOKEN

    {
      "name": "Set session_expiry claim",
      "supported_triggers": [
        { "id": "post-login" }
      ],
      "code": "exports.onExecutePostLogin = async (event, api) => {\n  if (event.session?.expires_at) {\n    const exp_date = new Date(event.session.expires_at);\n    api.idToken.setCustomClaim('session_expiry', Math.floor((exp_date.getTime()) / 1000));\n  }\n};"
    }
    ```

    後続の手順で必要になるため、レスポンスの `id` 値を控えておいてください。

    ### Action をデプロイする

    1. [Deploy an action](https://auth0.com/docs/api/management/v2/actions/post-deploy-action) エンドポイントに `POST` リクエストを送信します。

    ```http theme={null}
    POST https://YOUR_DOMAIN/api/v2/actions/actions/YOUR_ACTION_ID/deploy
    Authorization: Bearer YOUR_MANAGEMENT_API_TOKEN
    ```

    ### Action を Login トリガーにバインドする

    1. [Update trigger bindings](https://auth0.com/docs/api/management/v2/actions/patch-bindings) エンドポイントに `PATCH` リクエストを送信します。

    ```http theme={null}
    PATCH https://YOUR_DOMAIN/api/v2/actions/triggers/post-login/bindings
    Content-Type: application/json
    Authorization: Bearer YOUR_MANAGEMENT_API_TOKEN

    {
      "bindings": [
        {
          "ref": {
            "type": "action_id",
            "value": "YOUR_ACTION_ID"
          },
          "display_name": "Set session_expiry claim"
        }
      ]
    }
    ```

    <Callout icon="triangle-exclamation" color="#F59E0B" iconType="regular">
      `PATCH /api/v2/actions/triggers/post-login/bindings` リクエストを実行すると、既存のバインディングがすべて置き換えられます。ログインフロー内の既存の Actions を保持するには、まず `GET /api/v2/actions/triggers/post-login/bindings` で現在のバインディングを取得し、新しいバインディングとともに `PATCH` リクエストに含めてください。
    </Callout>

    次のプレースホルダー値を置き換えます。

    * **`YOUR_DOMAIN`**: Auth0 テナントのドメイン。例: `travel0.us.auth0.com`。
    * **`YOUR_MANAGEMENT_API_TOKEN`**: `create:actions`、`read:actions`、`update:actions` のスコープを持つ Management API トークン。
    * **`YOUR_ACTION_ID`**: Create Action のレスポンスで返される `id`。
  </Tab>
</Tabs>

<div id="use-session-expiry-with-auth0-sdks">
  ## Auth0 SDK でセッション有効期限を使用する
</div>

[Auth0 SDK](/docs/ja-jp/libraries) を使用し、前述の Post-Login Action を設定している場合、セッション有効期限は自動的に適用されます。SDK はログイン時に ID トークンから `session_expiry` を読み取り、セッションとともに保存します。現在時刻が `session_expiry` に達するか過ぎると、セッションは期限切れとして扱われます。

| SDK の種類                                  | 有効期限の適用方法                                                                                               |
| ---------------------------------------- | ------------------------------------------------------------------------------------------------------- |
| **通常の Web アプリ** (Next.js、Express、Python) | middleware がセッションをクリアし、`prompt=login` を指定してリダイレクトします。`getAccessToken()` は `SessionExpiredError` をスローします |
| **シングルページアプリ** (React、Angular、Vue)       | `getTokenSilently()` / `getAccessTokenSilently()` が拒否され、`prompt=login` を指定して再ログインがトリガーされます              |
| **モバイル** (iOS/Swift、Android/Kotlin)      | `CredentialsManager.credentials()` が `noCredentials` を返し、アプリの既存のログインフローで再認証が処理されます                      |

ID トークンに `session_expiry` クレームを注入するには、Post-Login Action が必要です。設定後にセッションの有効期限が切れると、SDK は他のセッション有効期限の場合と同様に動作し、ユーザーはログイン画面にリダイレクトされます。追加のエラー処理は必要ありません。

<div id="add-session-expiry-values-to-your-application">
  ## アプリケーションにセッションの有効期限の値を追加する
</div>

任意の手順として、アプリケーションにセッションの有効期限の値を追加できます。たとえば、アプリケーションで `session_expiry` を読み取って、セッションの有効期限が近いことをユーザーに警告したり、アプリケーション独自のセッション有効期間をupstream IdPの値に合わせたりできます。

<Tabs>
  <Tab title="シングルページアプリ">
    ```javascript theme={null}
    const claims = await auth0.getIdTokenClaims();
    const sessionExpiresAt = claims?.session_expiry;   // Unix seconds
    const remainingSeconds = sessionExpiresAt - Math.floor(Date.now() / 1000);
    ```
  </Tab>

  <Tab title="通常のWebアプリ">
    ```javascript theme={null}
    const session = await auth0.getSession();
    const sessionExpiresAt = session?.sessionExpiresAt;   // top-level field, Unix seconds
    const remainingSeconds = (sessionExpiresAt ?? Infinity) - Math.floor(Date.now() / 1000);
    ```
  </Tab>

  <Tab title="モバイル（Swift）">
    ```swift theme={null}
    credentialsManager.credentials { result in
        switch result {
        case .success(let credentials):
            let sessionExpiresAt = credentials.idToken?.session_expiry   // Unix seconds
        case .failure:
            startLogin()
        }
    }
    ```
  </Tab>
</Tabs>

読み取るたびに再検証することなく、Cookieや`localStorage`などの長期間保持されるストアに `session_expiry` の値を永続化しないでください。この値は、現在の実時間を基準にした場合にのみ意味を持ちます。

<div id="verify-in-tenant-logs">
  ## テナントログで確認する
</div>

セッション有効期限の強制を有効にした後、[テナントログ](/docs/ja-jp/deploy-monitor/logs)を確認して、セッション有効期限が正しく機能していることを検証します。

[**Auth0 Dashboard > Monitoring > Logs**](https://manage.auth0.com/#/logs)に移動し、設定したエンタープライズ接続を介して認証されたユーザーのログイン成功 (`s`) イベントを探します。上流IdPの`session_expiry`がテナントで設定した絶対セッション有効期間以下の場合、ログエントリには`idp_session_expiry`フィールド (秒単位のUnixタイムスタンプ) が含まれます。

```json theme={null}
{
  "type": "s",
  "description": "Success Login",
  "details": {
    "idp_session_expiry": 1782472241
  }
}
```

IdP が `session_expiry` クレームを送信せずにこの機能を有効にすると、ログインは次のエラーメッセージで失敗します: `The upstream Identity Provider did not return a session_expiry claim`.

<div id="disable-session-expiry-enforcement">
  ## セッション有効期限の強制を無効にする
</div>

<Tabs>
  <Tab title="Auth0 Dashboard">
    1. Auth0 Dashboard の [**Authentication > Enterprise**](https://manage.auth0.com/#/connections/enterprise) に移動します。
    2. 設定する接続を選択します。
    3. **設定** タブを選択します。
    4. **Use ID Token for Session Expiry** を無効にします。
    5. **Save** を選択します。
  </Tab>

  <Tab title="Management API">
    接続オプションで `id_token_session_expiry_supported` を `false` に設定します。

    ```http theme={null}
    PATCH https://YOUR_DOMAIN/api/v2/connections/YOUR_CONNECTION_ID
    Content-Type: application/json
    Authorization: Bearer YOUR_MANAGEMENT_API_TOKEN

    {
      "options": {
        "id_token_session_expiry_supported": false
      }
    }
    ```
  </Tab>
</Tabs>

<div id="learn-more">
  ## 詳細情報
</div>

* [セッションのライフサイクル](/docs/ja-jp/manage-users/sessions/session-lifecycle)
* [セッションの有効期間を設定する](/docs/ja-jp/manage-users/sessions/configure-session-lifetime)
* [Actions を使用したセッション](/docs/ja-jp/manage-users/sessions/manage-sessions-actions)
* [バックチャネルログアウト](/docs/ja-jp/authenticate/login/logout/back-channel-logout)
* [IPSIE SL1 OpenID Connect Profile](https://openid.net/specs/ipsie-openid-connect-sl1-profile-1_0.html)
