> ## 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 に登録されたアプリケーションの Cross-Origin Resource Sharing（CORS）を設定する方法を説明します。

# Cross-Origin Resource Sharing（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) + "*****マスク済み*****";
          }
          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)** のリストに追加する必要があります。
  * アプリケーションの **Settings** ビューで、**Allowed Web Origins** がリクエスト元のドメインに設定されていることを確認してください。URL にはサブドメイン用のワイルドカードを含めることができますが、ドメイン URL の後ろに相対パスを含めることはできません。詳細については、[サブドメイン用プレースホルダー](/ja/docs/get-started/applications/wildcards-for-subdomains) を参照してください。
  * [カスタムドメイン](/ja/docs/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. [Dashboard > Applications > Applications](https://manage.auth0.com/#/applications) に移動し、表示するアプリケーションの名前をクリックします。
2. **Cross-Origin Authentication** で、**Allow Cross-Origin Authentication** をオンにします。
3. **Allowed Origins (CORS)** を見つけて、アプリケーションのオリジン URL を入力します。Origin の詳細については、[Mozilla MDN Web Docs の Origin](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin) を参照してください。
4. **Save Changes** をクリックします。

<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](/ja/docs/libraries/auth0js) の `crossOriginVerification` メソッドを使用できます。

Chrome、Opera、Safari などのサポート対象外のブラウザでは、[カスタムドメイン](/ja/docs/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 でのトークン更新](https://support.auth0.com/center/s/article/troubleshoot-auth0-token-renewal-issues-in-safari-with-itp-enabled) にどのように影響するかの例を以下に示します。
</Callout>

1. アプリケーション内に、[Auth0.js](/ja/docs/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\. [Dashboard > Applications > Applications](https://manage.auth0.com/#/applications) に移動し、対象のアプリケーションを選択します。
3\. **Cross-Origin Authentication** の **Cross-Origin Verification Fallback URL** フィールドに、作成したコールバックページの URL を追加します。

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

4. **Save Changes** をクリックします。

詳細については、[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` エンドポイントが呼び出され、次のエラーが発生することがあります。

| Status | Code                          | Description                                                               |
| ------ | ----------------------------- | ------------------------------------------------------------------------- |
| `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 属性](/ja/docs/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 には secure 属性が必要です。そうでない場合、ブラウザの cookie jar に保存できません。

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

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

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