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

# データベース接続の新規ユーザーにアクションでカスタムユーザーIDを設定する方法

> データベース接続で新規ユーザーを作成する際にカスタムの`user_id`を設定する`pre-user-registration` アクションを記述し、システム間でIDの一貫性を保ったり、IDの形式を標準化したりできるようにします。

export const ReleaseStageNotice = ({feature, stage, plans, contact, terms}) => {
  const stageTextMap = {
    "beta": "Beta",
    "ea": "早期アクセス"
  };
  const stageText = stageTextMap[stage] || "製品リリース段階";
  const prsLink = "/docs/troubleshoot/product-lifecycle/product-release-stages";
  const linkify = (text, url) => {
    return <a href={url} target="_blank" rel="noreferrer" class="link">{text}</a>;
  };
  const includeDetails = (plans, contact, terms) => {
    const hasDetails = terms || plans || contact;
    if (!hasDetails) return null;
    return <span data-as="p">
            {plans && <>この機能は{linkify(`${plans}プラン`, "https://auth0.com/pricing")}でご利用いただけます。 </>}
            {contact && "参加をご希望の場合は、" + contact + "までお問い合わせください。 "}
            {terms && <>この機能を使用することにより、Oktaの該当する無料トライアル規約および{linkify("Master Subscription Agreement", "https://www.okta.com/legal")}に同意したものとみなされます。</>}
        </span>;
  };
  return <Warning>
            <span data-as="p">
                <strong>{feature}機能は現在、{linkify(stageText, prsLink)}です。</strong>
            </span>

            {includeDetails(plans, contact, terms)}
        </Warning>;
};

<ReleaseStageNotice feature="custom user ID assignment with Actions" stage="ea" terms="true" />

既定では、新しいユーザーを作成すると、Auth0はそのユーザーの一意な識別子として[`user_id`属性](/docs/ja-jp/manage-users/user-accounts/user-profiles/user-profile-structure#param-identities)を自動的に生成します。

データベース接続では、ユーザー作成時にカスタムユーザーIDを設定できます。形式の標準化やシステム間の一貫性が必要な場合は、独自のユーザーIDを指定するとよいでしょう。たとえば、次のようなケースです。

* 別のIDプロバイダーからAuth0へ移行する際に既存のユーザーID構造を維持し、トークン、監査ログ、統合の一貫性を保つ。

* UUID v4や連番の整数によるユーザーIDなど、特定の形式を必要とするデータシステムや課金システムとの互換性を確保する。

* 社内データベースやCRMの主キーとユーザーIDを一致させ、データの結合やレポート作成を簡素化する。

* テナント名やアプリのメタデータなど、既知の属性から決定論的にユーザーIDを組み立てる。

カスタムの`user_id`を設定するには、新しいユーザープロファイルの作成前に発生する[`pre-user-registration`トリガー](/docs/ja-jp/customize/actions/explore-triggers/pre-user-registration)に追加した[アクション](/docs/ja-jp/customize/actions/actions-overview)内で`api.user.setUserId()`を呼び出します。

<h2 id="how-user-ids-are-determined">
  ユーザーIDの決定方法
</h2>

ユーザープロファイル内の[`identities`配列](/docs/ja-jp/manage-users/user-accounts/user-profiles/user-profile-structure#param-identities)には、ユーザーが認証に使用する各IDプロバイダーの情報を含むオブジェクトが格納されます。カスタムユーザーIDを設定すると、データベース接続に対応する`identities`配列オブジェクトの`user_id`属性が設定されます。

カスタムの`identities`ユーザーIDを設定する方法は、ユーザーの作成方法によって異なります。次の表は、利用可能な作成方法と、`user_id`が設定される優先順位をまとめたものです。

| ユーザー作成方法 | `user_id`の優先順位 |
| - | - |
| [Authentication APIの新しいユーザーの作成エンドポイント](/docs/ja-jp/api/authentication/signup/create-a-new-user) (`POST /dbconnections/signup`) または[ユニバーサルログイン](/docs/ja-jp/authenticate/login/auth0-universal-login)でのサインアップ | <ol><li>`pre-user-registration`アクション内の`api.user.setUserId()`</li> <li>Auth0が生成したユーザーID</li></ol> |
| [Management APIのユーザーの作成エンドポイント](/docs/ja-jp/api/management/v2/users/post-users) (`POST /users`) | <ol><li>`pre-user-registration`アクション内の`api.user.setUserId()`</li> <li>[リクエスト本文で設定された`user_id`](/docs/ja-jp/api/management/v2/users/post-users#body-user-id)</li> <li>Auth0が生成したユーザーID</li></ol> |
| [自動移行](/docs/ja-jp/manage-users/user-migration/configure-automatic-migration-from-your-database)を有効にしたカスタムデータベース接続 | <ol><li>`pre-user-registration`アクション内の`api.user.setUserId()`</li> <li>[ログイン](/docs/ja-jp/authenticate/database-connections/custom-db/templates/login)および[ユーザーの取得](/docs/ja-jp/authenticate/database-connections/custom-db/templates/get-user)のデータベースアクションスクリプトから返される[正規化ユーザープロファイルの`user_id`属性](/docs/ja-jp/manage-users/user-accounts/user-profiles/user-profile-structure#param-user-id)</li><li>Auth0が生成したユーザーID</li></ol> |
| [一括ユーザーインポートジョブ](/docs/ja-jp/manage-users/user-migration/bulk-user-imports) | <ol><li>[一括インポートJSONの`user_id`プロパティ](/docs/ja-jp/manage-users/user-migration/bulk-user-import-schema#param-user-id)</li> <li>Auth0が生成したユーザーID</li></ol> |

まとめると、`pre-user-registration`アクション内で`api.user.setUserId()`により設定したユーザーIDは、カスタムユーザーIDを設定する他の方法よりも優先されます。ただし、一括インポートジョブでは`pre-user-registration`トリガーは発火しません。

また、Auth0はプロファイルのプライマリIDに基づいて、ユーザープロファイルの[ルートレベルの`user_id`](/docs/ja-jp/manage-users/user-accounts/user-profiles/user-profile-structure#param-user-id)を設定します。プライマリIDとは、`identities`配列の最初のIDです。

ルートレベルの`user_id`は、プライマリIDのユーザーIDの先頭に接続ストラテジーを付加した値です (たとえば`auth0|your_custom_id`) 。このルートレベルの`user_id`は、たとえば[`sub`クレーム](/docs/ja-jp/secure/tokens/json-web-tokens/json-web-token-claims)の値として使用されるため、ダウンストリームのシステムが接頭辞付きの値を想定しているか必ず確認してください。

<h2 id="set-custom-user-ids-with-a-pre-user-registration-action">
  `pre-user-registration` アクションでカスタムユーザーIDを設定する
</h2>

`pre-user-registration` アクションでカスタムの `user_id` を設定するには、アクションを作成し、ユーザーIDを任意の値に設定するコードを記述したうえで、そのアクションを `pre-user-registration` トリガーに追加します。

<Steps titleSize="h3">
  <Step title="アクションを作成する">
    **[Dashboard > Actions > Library](https://manage.auth0.com/#/actions/library)** に移動します。**\[Create Action]** を選択し、ドロップダウンメニューから **\[Create Custom Action]** を選択します。

    表示された **\[Create Action]** ウィンドウで、次の項目を入力します。

    * **Name**：「Set Custom User ID」など、アクションの名前を指定します。
    * **Trigger**：**\[Pre User Registration]** を選択します。
    * **Runtime**：使用するNodeランタイムを選択します。

    その後 **\[Create]** を選択すると、新しいアクションのコードエディターが開きます。
  </Step>

  <Step title="アクションのコードを記述する">
    アクションのコードエディターで、ユースケースに応じて `api.user.setUserId()` を使ってユーザーIDを設定する[アクションコードを記述](/docs/ja-jp/customize/actions/action-coding-guidelines)します。

    カスタムユーザーIDは、次の要件を満たす必要があります。

    * `user_id` は接続内で一意である必要があります。指定した `user_id` のユーザーがすでに存在する場合、作成は失敗します。

    * `user_id` は、Management APIの[ユーザー作成エンドポイントの `user_id` ボディパラメーター](/docs/ja-jp/api/management/v2/users/post-users#body-user-id)と同じ検証を通過する必要があります。

    ユーザーIDの問題でユーザー作成が失敗した場合は、[テナントログ](/docs/ja-jp/deploy-monitor/logs)で[ログタイプ `fs`](/docs/ja-jp/tenant-logs/auth-signup-fail/fs) (サインアップ失敗) を確認してください。

    <AccordionGroup>
      <Accordion title="例：UUID v4を生成する">
        Nodeに組み込まれている `crypto` モジュールを使ってUUID v4を生成できます。

        ```js wrap Example: Generate a UUID v4 theme={null}
        exports.onExecutePreUserRegistration = async (event, api) => {
          const crypto = require('crypto');
          api.user.setUserId(crypto.randomUUID());
        };
        ```
      </Accordion>

      <Accordion title="例：特定バージョンのUUIDを生成する">
        特定のUUIDバージョン (v1、v5、v7など) が必要な場合は、`uuid` npmパッケージを依存関係として追加し、アクション内で使用します。

        ```js wrap Example: Generate a specific UUID version theme={null}
        const { v7: uuidv7 } = require('uuid');

        exports.onExecutePreUserRegistration = async (event, api) => {
          api.user.setUserId(uuidv7());
        };
        ```
      </Accordion>

      <Accordion title="例：サインアップデータからIDを組み立てる">
        `app_metadata` の値など、サインアップデータから決定的なユーザーIDを組み立てることもできます。

        ```js wrap Example: Compose an ID from sign-up data theme={null}
        exports.onExecutePreUserRegistration = async (event, api) => {
          const externalId = event.user.app_metadata?.external_id;
          if (externalId) {
        	api.user.setUserId(externalId);
          }
        };
        ```
      </Accordion>
    </AccordionGroup>

    コードの記述と[アクションのテスト](/docs/ja-jp/customize/actions/test-actions)が完了したら、**\[導入]** を選択します。
  </Step>

  <Step title="アクションをトリガーに追加する">
    アクションを導入したら、**[Dashboard > Actions > Triggers > Pre User Registration](https://manage.auth0.com/#/actions/triggers/pre-user-registration)** に移動します。

    右側の **\[Add Action]** セクションの **\[Custom]** から、作成した新しいアクションを **\[Start]** と **\[Complete]** の間のフローにドラッグします。その後、**\[Apply]** を選択します。
  </Step>
</Steps>

<h2 id="limitations">
  制限事項
</h2>

* パスワードレス接続では、`pre-user-registration`トリガーによるカスタムユーザーIDの設定はサポートされていません。

* `pre-user-registration`トリガーは、一括インポートジョブでは起動しません。

* ソーシャル接続やエンタープライズ接続でログインするユーザーには、カスタムの`user_id`を設定できません。これらのIDは外部のIDプロバイダーから提供されるためです。

* 既存ユーザーの`user_id`は変更できません。
