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

> Auth0 Dashboard を使用して、Auth0 に登録されたアプリケーション向けに クロスオリジン リソース共有（CORS）を設定する方法を説明します。

# クロスオリジン リソース共有（CORS）を設定する

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>;
};

<Card title="始める前に">
  * セキュリティ上の理由から、アプリケーションのオリジン URL は承認済み URL として登録されている必要があります。まだアプリケーションの **Allowed Callback URLs** に追加していない場合は、**Allowed Origins (CORS)** のリストにも追加する必要があります。
  * アプリケーションの **設定** ビューにある **Allowed Web Origins** が、リクエスト元のドメインに設定されていることを確認してください。URL にはサブドメイン用のワイルドカードを含めることができますが、ドメイン URL の後に相対パスを含めることはできません。詳しくは、[サブドメイン用プレースホルダー](/docs/ja-jp/get-started/applications/wildcards-for-subdomains)を参照してください。
  * [カスタムドメイン](/docs/ja-jp/customize/custom-domains) を有効にしない場合は、クロスオリジン認証のフォールバックとして Auth0.js を使用する検証ページを作成する必要があります。
</Card>

クロスオリジン リソース共有 (CORS) は、アプリケーションがホストされているものとは異なるドメイン (オリジン) からデータ (リソース) を読み込めるようにする仕組みです。CORS ポリシーは、Web アプリケーションで一般的な同一オリジンポリシーに対する明示的な例外です。

たとえば、アプリケーション (app.mydomain.com) で、Ajax を使ってバックグラウンドで Google (fonts.google.com) からフォントを取得したい場合は、CORS を設定する必要があります。

<div id="configure-cross-origin-authentication">
  ## クロスオリジン認証を設定する
</div>

1. [Auth0 Dashboard > アプリケーション > アプリケーション](https://manage.auth0.com/#/applications) に移動し、詳細を表示するアプリケーションの名前をクリックします。
2. **Cross-Origin Authentication** で、**Allow Cross-Origin Authentication** をオンにします。
3. **Allowed Origins (CORS)** で、アプリケーションのオリジン URL を入力します。オリジンについて詳しくは、[Mozilla MDN Web Docs の Origin](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin) をご覧ください。
4. **変更を保存** をクリックします。

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  アプリケーションで CORS を使用する必要がない場合は、**Allow Cross-Origin Authentication** がオフになっていることを確認してください。
</Callout>

<div id="create-cross-origin-verification-page">
  ## クロスオリジン検証ページを作成する
</div>

サードパーティ Cookie を利用できないケースがあります。ブラウザのバージョンによってはサードパーティ Cookie をサポートしておらず、サポートしている場合でも、ユーザーの設定で無効になっていることがあります。

[サポートされているブラウザ](#browser-testing-support)では、サードパーティ Cookie が無効な場合に対応するため、アプリケーション内の専用ページで [Auth0.js SDK](/docs/ja-jp/libraries/auth0js) の `crossOriginVerification` メソッドを使用できます。

Chrome、Opera、Safari などのサポート対象外のブラウザでは、[カスタムドメイン](/docs/ja-jp/customize/custom-domains)を有効にしない限り、サードパーティ Cookie が無効な場合、クロスオリジン認証は機能しません。

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  **Safari** ではこの設定は "Prevent cross-site tracking" と表示され、[Intelligent Tracking Prevention](https://webkit.org/blog/7675/intelligent-tracking-prevention/) が使用されます。残念ながら、これにより認証シナリオではサードパーティ Cookie も利用できなくなります。たとえば、[Safari での token の更新](https://support.auth0.com/center/s/article/troubleshoot-auth0-token-renewal-issues-in-safari-with-itp-enabled) への影響については、こちらの例をご覧ください。
</Callout>

1. アプリケーションに、[Auth0.js](/docs/ja-jp/libraries/auth0js) の `WebAuth` をインスタンス化するページを作成します。作成したらすぐに `crossOriginVerification` を呼び出します。ページ名は任意です。

export const codeExample = `   <!-- callback-cross-auth.html -->

<head>
  <script src="https://cdn.auth0.com/js/auth0/9.11/auth0.min.js"></script>
  <script type="text/javascript">
    var auth0Client = new auth0.WebAuth({
      clientID: '{yourClientId}',
      domain: '{yourDomain}'
    });
    auth0Client.crossOriginVerification();
  </script>
</head>
`;

<AuthCodeBlock children={codeExample} language="text" />

サードパーティ Cookie を利用できない場合、Auth0.js は別のクロスオリジン検証フローを呼び出すために iframe をレンダリングします。
2\. [Auth0 Dashboard > アプリケーション > アプリケーション](https://manage.auth0.com/#/applications) に移動し、対象のアプリケーションを選択します。
3\. **Cross-Origin Authentication** で、作成したコールバックページの URL を **Cross-Origin Verification Fallback URL** フィールドに追加します。

<Warning>
  本番環境では、そのページの URL が `localhost` を指していないことを確認してください。このページは、組み込みログインフォームがホストされているものと同じドメイン上にあり、`https` スキームを使用している必要があります。
</Warning>

4. **変更を保存** をクリックします。

詳細については、[GitHub のクロスオリジン認証サンプル](https://github.com/auth0/lock/blob/master/support/callback-cross-auth.html) を参照してください。

<div id="error-codes-and-descriptions">
  ## エラーコードと説明
</div>

<Warning>
  エラーの説明は、人が読んで理解できることを目的としています。これらは予告なく変更される可能性があるため、コードで解析しないでください。
</Warning>

auth0.js (または Lock) を組み込みログインで使用すると、`/co/authenticate` エンドポイントが呼び出され、次のエラーが返されることがあります。

| ステータス | コード                           | 説明                                                                            |
| ----- | ----------------------------- | ----------------------------------------------------------------------------- |
| `400` | `invalid_request`             | リクエストボディが無効です。client\_id、credential\_type、username、otp、realm は、これらすべてのみが必須です。 |
| `400` | `unsupported_credential_type` | credential type パラメーターが不明です。                                                  |
| `400` | `invalid_request`             | レルム non-existent-connection は存在しません。                                          |
| `401` | `unauthorized_client`         | クロスオリジンログインは許可されていません。                                                        |
| `401` | `password_leaked`             | 現在使用しているパスワードが過去のデータ侵害 (このアプリケーション外) で漏えいしていたため、このログイン試行はブロックされました。           |
| `403` | `access_denied`               | メールアドレスまたはパスワードが正しくありません。                                                     |
| `403` | `access_denied`               | 認証エラー                                                                         |
| `403` | `blocked_user`                | ブロックされたユーザー                                                                   |
| `429` | `too_many_attempts`           | 複数回連続でログインに失敗したため、アカウントがブロックされました。ブロック解除方法については、ご希望の連絡先に通知をお送りしています。          |
| `429` | `too_many_attempts`           | 不審なログイン動作が検出されたため、以降の試行はブロックされます。管理者に連絡してください。                                |

さらに、`error` または `error_description` プロパティを含まない一般的な `403` エラーが返されることもあります。レスポンスボディには、次のような内容だけが含まれます。

`Origin https://test.app is not allowed.`

<div id="browser-testing-support">
  ## ブラウザでのテスト対応
</div>

次のブラウザでは、サードパーティ Cookie が無効になっている場合でも、クロスオリジン認証を使用できます。

* Microsoft Internet Explorer

<Card title="Samesite cookie 属性">
  以前は、[`samesite` cookie 属性](/docs/ja-jp/manage-users/cookies/samesite-cookie-attribute-changes)のオプションとして `true`、`false`、`strict`、`lax` がありました。この属性を手動で設定しなかった場合、Auth0 はデフォルト値として `false` を使用していました。

  2020 年 2 月から、Google Chrome v80 で Cookie の処理方法が変更されたため、Auth0 でもそれに合わせて次の変更が実施されました。

  * `samesite` 属性が設定されていない Cookie は、`lax` に設定されます。
  * `sameSite=none` が設定された Cookie はセキュアである必要があります。そうでない場合、ブラウザの cookie jar に保存できません。

  これらの変更は、セキュリティを向上させ、クロスサイトリクエストフォージェリ (CSRF) 攻撃の軽減に役立てることを目的としています。
</Card>

<div id="learn-more">
  ## 詳しく見る
</div>

* [埋め込みログイン](/docs/ja-jp/authenticate/login/embedded-login)
* [クロスオリジン認証](/docs/ja-jp/authenticate/login/cross-origin-authentication)
* [アプリケーション設定](/docs/ja-jp/get-started/applications/application-settings)
* [SameSite Cookie属性の変更](/docs/ja-jp/manage-users/cookies/samesite-cookie-attribute-changes)
