> ## 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.

> マルチブランドおよびマルチリージョンでの展開に向けて、1 つの Auth0 テナント内で複数のカスタムドメインを設定・管理する方法を学びます。

# 複数のカスタムドメイン

export const AuthCodeGroup = ({children, dropdown}) => {
  const [processedChildren, setProcessedChildren] = useState(children);
  useEffect(() => {
    let unsubscribe = null;
    function init() {
      unsubscribe = window.autorun(() => {
        const processChildren = node => {
          if (typeof node === "string") {
            let processedNode = node;
            for (const [key, value] of window.rootStore.variableStore.values.entries()) {
              const escapedKey = key.replaceAll(/[.*+?^${}()|[\]\\]/g, (String.raw)`\$&`);
              processedNode = processedNode.replaceAll(new RegExp(escapedKey, "g"), value);
            }
            return processedNode;
          } else if (Array.isArray(node)) {
            return node.map(processChildren);
          } else if (node && node.props && node.props.children) {
            return {
              ...node,
              props: {
                ...node.props,
                children: processChildren(node.props.children)
              }
            };
          }
          return node;
        };
        setProcessedChildren(processChildren(children));
      });
    }
    if (window.rootStore) {
      init();
    } else {
      window.addEventListener("adu:storeReady", init);
    }
    return () => {
      window.removeEventListener("adu:storeReady", init);
      unsubscribe?.();
    };
  }, [children]);
  return <CodeGroup dropdown={dropdown}>{processedChildren}</CodeGroup>;
};

export const AuthCodeBlock = ({filename, icon, language, highlight, children}) => {
  const [displayText, setDisplayText] = useState(children);
  const [copyText, setCopyText] = useState(children);
  const wrapperRef = React.useRef(null);
  useEffect(() => {
    let unsubscribe = null;
    function init() {
      if (!window.autorun || !window.rootStore) {
        return;
      }
      unsubscribe = window.autorun(() => {
        let processedChildrenForDisplay = children;
        let processedChildrenForCopy = children;
        for (const [key, value] of window.rootStore.variableStore.values.entries()) {
          const escapedKey = key.replaceAll(/[.*+?^${}()|[\]\\]/g, (String.raw)`\$&`);
          let displayValue = value;
          if (key === "{yourClientSecret}" && value !== "{yourClientSecret}") {
            displayValue = value.substring(0, 3) + "*****MASKED*****";
          }
          processedChildrenForDisplay = processedChildrenForDisplay.replaceAll(new RegExp(escapedKey, "g"), displayValue);
          processedChildrenForCopy = processedChildrenForCopy.replaceAll(new RegExp(escapedKey, "g"), value);
        }
        setDisplayText(processedChildrenForDisplay);
        setCopyText(processedChildrenForCopy);
      });
    }
    if (window.rootStore) {
      init();
    } else {
      window.addEventListener("adu:storeReady", init);
    }
    return () => {
      window.removeEventListener("adu:storeReady", init);
      unsubscribe?.();
    };
  }, [children]);
  useEffect(() => {
    if (!wrapperRef.current) return;
    const originalWriteText = navigator.clipboard.writeText.bind(navigator.clipboard);
    let isOverriding = false;
    const handleClick = e => {
      const button = e.target.closest('[data-testid="copy-code-button"]');
      if (!button || !wrapperRef.current.contains(button)) return;
      isOverriding = true;
      navigator.clipboard.writeText = text => {
        if (isOverriding) {
          isOverriding = false;
          navigator.clipboard.writeText = originalWriteText;
          return originalWriteText(copyText);
        }
        return originalWriteText(text);
      };
      setTimeout(() => {
        if (isOverriding) {
          isOverriding = false;
          navigator.clipboard.writeText = originalWriteText;
        }
      }, 100);
    };
    const wrapper = wrapperRef.current;
    wrapper.addEventListener('click', handleClick, true);
    return () => {
      wrapper.removeEventListener('click', handleClick, true);
      if (navigator.clipboard.writeText !== originalWriteText) {
        navigator.clipboard.writeText = originalWriteText;
      }
    };
  }, [copyText]);
  return <div ref={wrapperRef}>
      <CodeBlock filename={filename} icon={icon} language={language} lines highlight={highlight}>
        {displayText}
      </CodeBlock>
    </div>;
};

Auth0 では、<Tooltip tip="カスタムドメイン: 独自の、いわゆるバニティ名を使用するサードパーティドメイン。" cta="用語集を見る" href="/docs/ja-jp/glossary?term=custom+domain">カスタムドメイン</Tooltip> を使うことで、自社のブランドや製品に合わせてログイン体験を統一できます。複数のカスタムドメインを利用すると、1 つの Auth0 テナント内で複数のカスタムドメインを設定できます。この機能は、Public Cloud と Private Cloud の両方のデプロイ環境において、Enterprise のお客様にご利用いただけます。

<div id="prerequisites">
  ## 前提条件
</div>

MCD を使い始める前に、以下の要件を確認してください。

* お使いのテナントが Enterprise プラン ([Public Cloud または Private Cloud でのデプロイ](/docs/ja-jp/deploy-monitor/deployment-options)) であること。詳細については、
  「Manage Subscriptions」を参照してください。
* ご利用の Enterprise プランには、1 テナントあたり最大 20 個のカスタムドメインの基本利用枠が含まれています。
* 基本利用枠を超える追加のカスタムドメインは、アドオン SKU として利用できます。詳細については Auth0 の営業担当までお問い合わせください。
* 設定したカスタムドメインの所有権を証明できる必要があります。

<div id="configure-multiple-custom-domains">
  ## 複数のカスタムドメインを設定する
</div>

<Tooltip tip="Management API: お客様が管理タスクを実行できるようにする製品です。" cta="用語集を見る" href="/docs/ja-jp/glossary?term=Auth0+Dashboard">Auth0 Dashboard</Tooltip> または <Tooltip tip="Management API: お客様が管理タスクを実行できるようにする製品です。" cta="用語集を見る" href="/docs/ja-jp/glossary?term=Management+API">Management API</Tooltip> を使用すると、テナントに複数のカスタムドメインを追加して管理できます。

<Tabs>
  <Tab title="Auth0 Dashboard">
    Auth0 Dashboard でカスタムドメインを作成するには:

    1. **Auth0 Dashboard** > **Branding > Custom Domains** に移動します。
    2. **+Add custom domain** を選択します。
    3. 設定フォームで、次の情報を入力します。

       * **Domain:** 自分が所有する[完全修飾ドメイン名](https://en.wikipedia.org/wiki/Fully_qualified_domain_name)。例: `my.custom-domain.com`
       * **Certificate type:** [**Auth0-managed certificates**](/docs/ja-jp/customize/custom-domains/auth0-managed-certificates) または [**Self-managed certificates**](/docs/ja-jp/customize/custom-domains/self-managed-certificates) を選択します。
       * **Metadata (Key/Value):** `region`、`client_name`、`client_id` などの任意のメタデータを追加して、ドメインの整理やフィルタリングに役立てます。
    4. カスタムドメインの詳細を設定したら、**Save** を選択します。

    新しく追加したドメイン名は、検証が完了するまで `pending` と表示されます。

    #### ドメインの表示と管理

    Custom Domains ページには、設定済みのすべてのドメインが表示されます。次のことができます。

    * **Search**: 検索ボックスを使って、名前でドメインを検索する
    * **Filter**: 検証ステータス、証明書の種類、またはメタデータの値でドメインを絞り込む
    * **Sort**: 名前、作成日、または検証ステータスでドメインを並べ替える
    * **View details**: 任意のドメインをクリックして、詳細な設定、検証ステータス、証明書情報を確認する
    * **Set default**: ドメインをテナントのデフォルトドメインとして指定する

    これらの機能により、テナント内の多数のカスタムドメインを効率的に管理できます。
  </Tab>

  <Tab title="Management API">
    Management API を使用してカスタムドメインを作成するには、Management API の使用が承認されたマシン間 (M2M) アプリケーションが必要です。詳細については、[Management API Access Tokens](/docs/ja-jp/secure/tokens/access-tokens/management-api-access-tokens) を参照してください。

    1. [Auth0 Dashboard > Applications > Applications](https://manage.auth0.com/#/applications) に移動し、**Create Application** を選択します。
    2. アプリケーションにわかりやすい名前を入力し、**Machine to Machine Applications** を選択します。次に、**Create** を選択します。
    3. **APIs** ビューに切り替え、`Auth0 Management API` のトグルをオンにします。
    4. 行を展開し、API の権限を設定します。MCD では、次の項目を選択する必要があります。

       * `read:custom_domains`
       * `create:custom_domains`
       * `update:custom_domains`
       * `delete:custom_domains`
    5. **Update** を選択します。
    6. **Client ID**、**Client Secret**、**Domain** を確認するには、**Settings** タブに移動します。
    7. アクセストークンを取得して保存するには、[Management API アクセストークンを取得する](/docs/ja-jp/secure/tokens/access-tokens/management-api-access-tokens/get-management-api-access-tokens-for-production)を参照してください。

    #### カスタムドメインの作成

    新しいカスタムドメインを作成するには、`POST` リクエストを `/api/v2/custom-domains` エンドポイントに送信します。上記で取得した資格情報を使用して Management API エクスプローラーで新しいカスタムドメインを作成する方法については、以下の例を参照してください:

    <AuthCodeGroup>
      ```bash cURL theme={null}
      curl --request POST \
        --url 'https://{yourDomain}/api/v2/custom-domains' \
        --header 'accept: application/json' \
        --header 'authorization: Bearer {yourMgmtApiAccessToken}' \
        --header 'content-type: application/json' \
        --data '{ 
       "domain": "your.example-custom-domain.com", 
       "type": "auth0_managed_certs", 
       "tls_policy": "recommended", 
       "custom_client_ip_header": "true-client-ip", 
       "domain_metadata": {
          "environment": "development"} 
      }'
      ```

      ```csharp C# theme={null}
      var client = new RestClient("https://{yourDomain}/api/v2/custom-domains");
      var request = new RestRequest(Method.POST);
      request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}");
      request.AddHeader("content-type", "application/json");
      request.AddHeader("accept", "application/json");
      request.AddParameter("application/json", "{ 
       "domain": "your.example-custom-domain.com", 
       "type": "auth0_managed_certs", 
       "tls_policy": "recommended", 
       "custom_client_ip_header": "true-client-ip", 
       "domain_metadata": {
       "environment": "development"} 
      }", ParameterType.RequestBody);
      IRestResponse response = client.Execute(request);
      ```

      ```go Go theme={null}
      package main

      import (
      	"fmt"
      	"strings"
      	"net/http"
      	"io/ioutil"
      )

      func main() {

      	url := "https://{yourDomain}/api/v2/custom-domains"

      	payload := strings.NewReader("{ 
       "domain": "your.example-custom-domain.com", 
       "type": "auth0_managed_certs", 
       "tls_policy": "recommended", 
       "custom_client_ip_header": "true-client-ip", 
       "domain_metadata": {
          "environment": "development"} 
      }")

      	req, _ := http.NewRequest("POST", url, payload)

      	req.Header.Add("authorization", "Bearer {yourMgmtApiAccessToken}")
      	req.Header.Add("content-type", "application/json")
      	req.Header.Add("accept", "application/json")

      	res, _ := http.DefaultClient.Do(req)

      	defer res.Body.Close()
      	body, _ := ioutil.ReadAll(res.Body)

      	fmt.Println(res)
      	fmt.Println(string(body))

      }
      ```

      ```java Java theme={null}
      HttpResponse<String> response = Unirest.post("https://{yourDomain}/api/v2/custom-domains")
        .header("authorization", "Bearer {yourMgmtApiAccessToken}")
        .header("content-type", "application/json")
        .header("accept", "application/json")
        .body("{ 
       "domain": "your.example-custom-domain.com", 
       "type": "auth0_managed_certs", 
       "tls_policy": "recommended", 
       "custom_client_ip_header": "true-client-ip", 
       "domain_metadata": {
          "environment": "development"} 
      }")
        .asString();
      ```

      ```javascript Node.JS theme={null}
      var axios = require("axios").default;

      var options = {
        method: 'POST',
        url: 'https://{yourDomain}/api/v2/custom-domains',
        headers: {
          authorization: 'Bearer {yourMgmtApiAccessToken}',
          'content-type': 'application/json',
          accept: 'application/json'
        },
        data: {
          domain: 'your.example-custom-domain.com',
          type: 'auth0_managed_certs',
          tls_policy: 'recommended',
          custom_client_ip_header: 'true-client-ip',
          domain_metadata: {environment: 'development'}
        }
      };

      axios.request(options).then(function (response) {
        console.log(response.data);
      }).catch(function (error) {
        console.error(error);
      });
      ```

      ```php PHP theme={null}
      $curl = curl_init();

      curl_setopt_array($curl, [
        CURLOPT_URL => "https://{yourDomain}/api/v2/custom-domains",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => "{ 
       "domain": "your.example-custom-domain.com", 
       "type": "auth0_managed_certs", 
       "tls_policy": "recommended", 
       "custom_client_ip_header": "true-client-ip", 
       "domain_metadata": {
          "environment": "development"} 
      }",
        CURLOPT_HTTPHEADER => [
          "accept: application/json",
          "authorization: Bearer {yourMgmtApiAccessToken}",
          "content-type: application/json"
        ],
      ]);

      $response = curl_exec($curl);
      $err = curl_error($curl);

      curl_close($curl);

      if ($err) {
        echo "cURL Error #:" . $err;
      } else {
        echo $response;
      }
      ```

      ```python Python theme={null}
      import http.client

      conn = http.client.HTTPSConnection("")

      payload = "{ 
       "domain": "your.example-custom-domain.com", 
       "type": "auth0_managed_certs", 
       "tls_policy": "recommended", 
       "custom_client_ip_header": "true-client-ip", 
       "domain_metadata": {
          "environment": "development"} 
      }"

      headers = {
          'authorization': "Bearer {yourMgmtApiAccessToken}",
          'content-type': "application/json",
          'accept': "application/json"
          }

      conn.request("POST", "/{yourDomain}/api/v2/custom-domains", payload, headers)

      res = conn.getresponse()
      data = res.read()

      print(data.decode("utf-8"))
      ```

      ```ruby Ruby theme={null}
      require 'uri'
      require 'net/http'
      require 'openssl'

      url = URI("https://{yourDomain}/api/v2/custom-domains")

      http = Net::HTTP.new(url.host, url.port)
      http.use_ssl = true
      http.verify_mode = OpenSSL::SSL::VERIFY_PEER

      request = Net::HTTP::Post.new(url)
      request["authorization"] = 'Bearer {yourMgmtApiAccessToken}'
      request["content-type"] = 'application/json'
      request["accept"] = 'application/json'
      request.body = "{ 
       "domain": "your.example-custom-domain.com", 
       "type": "auth0_managed_certs", 
       "tls_policy": "recommended", 
       "custom_client_ip_header": "true-client-ip", 
       "domain_metadata": {
          "environment": "development"} 
      }"

      response = http.request(request)
      puts response.read_body
      ```
    </AuthCodeGroup>

    成功すると、新しいカスタムドメインの詳細 (確認ステータスを含む) が以下のように返されます。`status` の初期値は `pending` です。

    ```json lines theme={null}
    {
        "custom_domain_id": "cd_abc123def456",
        "domain": "your.example-custom-domain.com",
        "primary": false,
        "status": "pending",
        "type": "auth0_managed_certs",
        "verification": {
            "methods": [
                {
                    "name": "CNAME",
                    "record": "yourtenant.auth0.com",
                    "domain": "your.example-custom-domain.com"
                }
            ]
        },
        "tls_policy": "recommended",
        "domain_metadata": {
            "environment": "development"
        }
    }
    ```
  </Tab>
</Tabs>

<div id="mcd-features">
  ## MCD の機能
</div>

MCD には、Auth0 の実装をより効率的に管理し、ユーザーエクスペリエンスを向上させるための重要な機能が数多く用意されています。使用するカスタムドメインの所有権の確保と、ドメイン名レジストラへの登録はお客様の責任で行っていただきます。

[Auth0 Management API](https://auth0.com/docs/api/management/v2/custom-domains/get-custom-domains) は、これらのカスタムドメインに対する **作成、読み取り、更新、削除、検証** の各操作を包括的にサポートしており、ライフサイクル全体をプログラムで完全に制御できます。

MCD は、次の Auth0 Management SDK でサポートされています: [Node.js](https://github.com/auth0/node-auth0)、[Go](https://github.com/auth0/go-auth0)、[Python](https://github.com/auth0/auth0-python)、[Java](https://github.com/auth0/auth0-java)、および [.NET](https://github.com/auth0/auth0.net)。認証 SDK は、アプリケーションで設定すると、カスタムドメインで自動的に動作します。

<div id="default-domain">
  ### デフォルトドメイン
</div>

複数のカスタムドメインが設定されている場合は、そのうちの 1 つを**デフォルトドメイン**として指定できます。デフォルトドメインは、Auth0 Management API エンドポイントでドメイン情報が必要なものの、`auth0-custom-domain` ヘッダーでカスタムドメインが明示的に指定されていない場合に使用されます。この情報は、ドメインごとの内容でメール通知 (例: パスワードリセットやメールアドレスの確認) をカスタマイズするために使用されます。

デフォルトドメインを設定するには、次の手順に従います。

1. **Auth0 Dashboard** > **Branding > Custom Domains** に移動します
2. 一覧から、デフォルトとして設定するドメインを探します
3. そのドメインの **Set as Default** ボタンをクリックします

Management API を使用してカスタムドメインの設定を更新し、デフォルトドメインを設定することもできます。設定後は、`auth0-custom-domain` ヘッダーで特定のドメインが指定されていない限り、メール通知のカスタマイズにデフォルトドメインが自動的に使用されます。

<Callout icon="info" color="#0EA5E9" iconType="regular">
  デフォルトドメインを設定すると、通知をトリガーする Management API エンドポイントでは `auth0-custom-domain` ヘッダーが省略可能になります。これらのエンドポイントを呼び出す際にカスタムドメインを指定しない場合、Auth0 はメールのカスタマイズに自動的にデフォルトドメインを使用します。
</Callout>

<div id="domain-verification">
  ### ドメインの検証
</div>

ドメイン名の所有権を確認する方法は、選択した管理タイプによって異なります。

| ドメインの種類                                                                              | 検証方法           | 詳細                                       |
| ------------------------------------------------------------------------------------ | -------------- | ---------------------------------------- |
| **[Auth0-Managed](/docs/ja-jp/customize/custom-domains/auth0-managed-certificates)** | CNAME DNS レコード | このレコードを設定すると、ドメインの所有権が確認され、ドメインが有効になります。 |
| **[Self-Managed](/docs/ja-jp/customize/custom-domains/self-managed-certificates)**   | TXT DNS レコード   | TXT レコードの詳細は、Create API のレスポンスで提供されます。   |

Auth0 によってカスタムドメインが確認されると、すぐにそれを使用してユーザー向けの Auth0 機能を設定できます。詳しくは、[Configure Features to Use Custom Domains](/docs/ja-jp/customize/custom-domains/configure-features-to-use-custom-domains) を参照してください。

<div id="metadata-for-enhanced-management">
  ### 管理を強化するためのメタデータ
</div>

整理しやすくし、将来的なカスタマイズに備えるため、各カスタムドメインに最大10個のメタデータフィールドを設定できます。今後のリリースでは、これらのメタデータフィールドによって、メールテンプレート、<Tooltip tip="Universal Login: アプリケーションは、ユーザーの本人確認のために、Auth0 の Authorization Server でホストされる Universal Login にリダイレクトされます。" cta="用語集を見る" href="/docs/ja-jp/glossary?term=Universal+Login">Universal Login</Tooltip>、および認証ロジックの高度なカスタマイズが可能になります。

<div id="customize-email-templates">
  ### メールテンプレートをカスタマイズする
</div>

カスタムドメインの情報を活用してメールテンプレートをパーソナライズし、ブランドイメージを反映させることで、一貫したユーザー体験を実現できます。そのために、MCD では Liquid Syntax で使用できる `custom_domain.domain` 変数を提供しています。

たとえば、メールテンプレートの **From Address** を `support@{{ custom_domain.domain }}` に設定すると、`support@my.custom-domain.com` として展開されます。この変数は、**From Address**、**Subject**、**Message** の各フィールドで Liquid Syntax を通じて利用できます。詳しくは、[メールテンプレートをカスタマイズする](/docs/ja-jp/customize/email/email-templates) をご覧ください。

<div id="customize-email-handling-using-the-management-api">
  #### Management API を使用してメール処理をカスタマイズする
</div>

Multiple Custom Domains を設定し、[メールでカスタムドメインを使用](/docs/ja-jp/customize/custom-domains/configure-features-to-use-custom-domains#use-custom-domains-in-emails) を有効にしている場合は、Auth0 Management API の使用時に `auth0-custom-domain` HTTP ヘッダーを利用できます。このヘッダーは、メールテンプレート内で `domain object` の値として渡されます。

次の Management API エンドポイントでは、`auth0-custom-domain` HTTP ヘッダーを受け付けます。

* [メールアドレス確認メールを送信する](https://auth0.com/docs/api/management/v2#!/Jobs/post_verification_email)
* [メールアドレス確認チケットを作成する](https://auth0.com/docs/api/management/v2/tickets/post-email-verification)
* [組織への招待を作成する](https://auth0.com/docs/api/management/v2/organizations/post-invitations)
* [ユーザーを作成する](https://auth0.com/docs/api/management/v2/users/post-users)
* [多要素認証の登録チケットを作成する](https://auth0.com/docs/api/management/v2/guardian/post-ticket)
* [パスワード変更チケットを作成する](https://auth0.com/docs/api/management/v2/tickets/post-password-change)
* [ユーザーを更新する](https://auth0.com/docs/api/management/v2/users/patch-users-by-id)

例: [Node.js](https://github.com/auth0/node-auth0) 用 Auth0 SDK を使用してパスワード変更チケットを作成する場合。

```javascript lines theme={null}
import { ManagementClient, CustomDomainHeader } from "auth0";

// クライアントレベル: ホワイトリストに登録されたエンドポイントに自動適用
const auth0 = new ManagementClient({
    domain: '{yourDomain}',
    clientId: '{yourClientId}',
    clientSecret: '{yourClientSecret}',
    withCustomDomainHeader: 'my-custom-domain.com',});

(async () => {
    try {
        const ticket = await auth0.tickets.changePassword({
            user_id: 'auth0|abc123',
            result_url: 'https://example.com/success'
        });
        console.log('Password change ticket created:', ticket.data.ticket);
    } catch (err) {
        console.error('Error creating password change ticket:', err);
    }
})();

// または、リクエストごとに個別指定する方法
const reqOptions = {
    ...CustomDomainHeader('my-custom-domain.com'),
};
const ticket = await auth0.tickets.changePassword(
    { user_id: 'auth0|abc123', result_url: 'https://example.com/success' },
    reqOptions
);
```

レスポンス例: チケットURLを生成するためのヘッダーに、カスタムドメインが渡されます。

```json lines theme={null}
{
    "ticket": "https://my-custom-domain.com/u/reset-verify?ticket=abc123"
}
```

<div id="response-messages">
  ##### レスポンスメッセージ
</div>

`auth0-custom-domain` HTTP ヘッダーを指定すると、次の追加レスポンスが返される場合があります。

| HTTP ステータスコード | メッセージ                                    |
| ------------- | ---------------------------------------- |
| `409`         | テナントに、検証済みのカスタムドメインが複数存在します。             |
| `400`         | そのテナントにはカスタムドメインが存在しません。                 |
| `400`         | `auth0-custom-domain` HTTP ヘッダーの形式が無効です。 |

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  MCD を有効にし、Auth0 Dashboard を使用して Email Templates を設定している場合、Try 機能は標準の Auth0 ドメインではなく、既定のカスタムドメインを使用して実行されます。
</Callout>

<div id="application-url-placeholders">
  ### アプリケーション URL プレースホルダー
</div>

コールバック URL、ログアウト URL、Application Login URI (`initiate_login_uri`) などのアプリケーション URL では、カスタムドメインのメタデータを動的なプレースホルダーとして使用できます。これにより、実行時に各カスタムドメインをそれぞれ異なるアプリケーション URL に対応付けることができます。詳しくは、[カスタムドメイン URL プレースホルダー](/docs/ja-jp/get-started/applications/wildcards-for-subdomains#custom-domain-url-placeholders)を参照してください。

<div id="multiple-custom-domains-with-actions">
  ### 複数のカスタムドメインでのActionsの利用
</div>

Auth0の[Actions](/docs/ja-jp/customize/actions)を使うと、カスタムドメインに応じて、それぞれのトランザクションを処理するカスタムロジックを作成できます。

たとえば、ユーザーを関連する[organization](/docs/ja-jp/manage-users/organizations)に誘導するActionを作成したり、特定の[アクセス制御ポリシー](/docs/ja-jp/customize/actions/use-cases#api-authorization)を適用したりできます。

これを実現するために、Post-Login Actionsでは`event.custom_domain`オブジェクトを利用でき、認証フローで使用されているカスタムドメインを取得できます。

<div id="use-case-restrict-user-access-to-an-organization-based-on-custom-domain">
  #### ユースケース: カスタムドメイン に基づいてユーザーの Organization へのアクセスを制限する
</div>

ドメインの許可リストと拒否リスト (例: `allow_domains` と `deny_domains`) を Organization のメタデータに保存します。

以下を行う Action を作成します。

1. `event.custom_domain?.domain` プロパティからユーザーのドメインを取得する
2. そのドメインを両方のリストと照合する
3. 結果に応じて、ユーザーのアクセスを許可または拒否する

```js lines expandable theme={null}
exports.onExecutePostLogin = async (event, api) => {
    const customDomain = event?.custom_domain?.domain;
    
    console.log(`org ${event?.organization?.name} accessed from domain ${customDomain || event?.request?.hostname}`);

    if (event?.organization?.metadata?.deny_domains && event?.organization?.metadata?.allow_domains) {
        console.warn(`[WARNING] configuration issue. org ${event?.organization?.name} has both deny_domains and allow_domains`);
    }

    // 拒否 (A) または許可 (B) のいずれかを確認する（両方同時は不可）
    // (A) organizationの deny_list を確認する
    const isDomainDenied = () =>
        (event?.organization?.metadata?.deny_domains ? event?.organization?.metadata?.deny_domains.split(',').map(d => d.trim()).includes(customDomain) : false);
        
    if (isDomainDenied()) {
        return api.access.deny(`access to org ${event?.organization?.name} not allowed on domain ${customDomain}`);
    }

    // (B) organizationの allow_list を確認する
    const isDomainAllowed = () =>
        (event?.organization?.metadata?.allow_domains ? event?.organization?.metadata?.allow_domains.split(',').map(d => d.trim()).includes(customDomain) : false);
        
    if (!isDomainAllowed()) {
        return api.access.deny(`access to org ${event?.organization?.name} not allowed on domain ${customDomain}`);
    }
};
```

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  MCD では、`event.custom_domain` オブジェクトを通じて、Actions からカスタムドメインのメタデータにアクセスできます。この情報をテナントで設定したカスタムドメインのメタデータとあわせて使用することで、Actions 内でドメイン固有のロジックを実装できます。
</Callout>

<div id="custom-domain-attributes">
  ### カスタムドメインの属性
</div>

MCD では、カスタムドメインの検証と SSL/TLS 証明書の管理に関する以下の属性を提供しています。これらの属性により、カスタムドメインのプロビジョニング状況や運用状況をより細かく把握できます。

<div id="updated-attributes">
  #### 更新された属性
</div>

| 属性       | 説明                                                                                                                              |
| -------- | ------------------------------------------------------------------------------------------------------------------------------- |
| `status` | `status` 属性に、新しい列挙値 `failed` が追加されました。この値は、カスタムドメインの検証プロセスでエラーが発生し、検証に失敗したことを示します。既存のサポート対象の値 `pending` および `ready` に加えて利用できます。 |

<div id="new-attributes">
  #### 新しい属性
</div>

以下の属性は、Auth0 管理ドメインでのみサポートされています。

| 属性                                  | 説明                                                                                                                             |
| ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| `verification.status`               | DNS レコードの検証プロセスのステータスです。指定可能な値は `verified`、`pending`、`failed` です。                                                              |
| `verification.error_msg`            | `verification.status` が失敗を示している場合、この文字列属性には、検証失敗の状況を説明するわかりやすいエラーメッセージが格納されます。                                                 |
| `verification.last_verified_at`     | このタイムスタンプ属性には、カスタムドメインの最後の検証成功日時が記録されます。このタイムスタンプの形式は ISO 8601 に準拠します。                                                         |
| `certificate`                       | このオブジェクトには、カスタムドメインに関連付けられた SSL/TLS 証明書に関する情報が含まれます。                                                                           |
| `certificate.status`                | この属性は、SSL/TLS 証明書の現在のプロビジョニングステータスを示します。指定可能な値には、`provisioning`、`provisioned`、`provisioning_failed`、`renewing_failed` などがあります。 |
| `certificate.error_msg`             | `certificate.status` が `provisioning_failed` または `renewing_failed` の場合、この文字列属性には、失敗の理由を説明するわかりやすいエラーメッセージが格納されます。              |
| `certificate.certificate_authority` | この文字列属性は、カスタムドメイン用の SSL/TLS 証明書を発行した認証局を指定します。                                                                                 |
| `certificate.renews_before`         | Auth0 管理のカスタムドメインでは、この新しいタイムスタンプ属性は、SSL/TLS 証明書を更新する必要がある期限の日時を示します。このタイムスタンプの形式は ISO 8601 に準拠します。                             |

<div id="limitations">
  ### 制限事項
</div>

以下の制限は、複数のカスタムドメインに適用されます。

* **WebAuthn/Passkeys**:
  * 各カスタムドメインでは、パスキーの登録が個別に管理されます。あるカスタムドメインで登録したパスキーは、その特定の Relying Party ID (RP ID) に紐づいているため、他のドメインでは使用できません。
  * ユーザーが Domain A でローミングセキュリティキーを登録し、Domain B 経由でログインしようとした場合、認証は単に失敗するだけではありません。代わりに、RP ID が一致しないため、システムは直ちに新しい登録画面を表示します。
