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

# Cross-Originリソース共有を構成する

> Auth0 Dashboardを使用して、Auth0に登録されたアプリケーションのCross-Originリソース共有（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="Before you start">
  * セキュリティ上の理由により、アプリケーションのオリジンURLが承認済みURLのリストに含まれている必要があります。アプリケーションの **Allowed Callback URLs（許可されているコールバックURL）** に追加されていない場合は、**Allowed Origins (CORS)（許可されているオリジン（CORS））** のリストに追加する必要があります。
  * **Allowed Web Origins（許可されているWebオリジン）** が、アプリケーションの **Settings（設定）** ビューで要求を行うドメインに設定されていることを確認してください。URLはサブドメインにワイルドカードを含めることができますが、ドメインURLの後に相対パスは使用できません。詳細については、「[サブドメインのプレースホルダー](https://auth0.com/docs/get-started/applications/wildcards-for-subdomains)」をお読みください。
  * [カスタムドメイン](https://auth0.com/docs/customize/custom-domains)を有効化しない場合は、cross-origin認証のフォールバックとして、Auth0.jsを使う検証ページを作成する必要があります。
</Card>

Auth0では、[ユニバーサルログイン](/docs/ja-jp/authenticate/login/auth0-universal-login)を通じた認証トランザクションの処理を強く推奨しています。そうすることにより、ユーザーの認証が最も簡単で安全になります。ただし、状況によっては、ログインをアプリケーションに直接埋め込む必要がある場合もあります。埋め込みログインが必要な場合は、アプリケーションでcross-originリソース共有（CORS）を構成する必要があります。

CORSは、<Tooltip data-tooltip-id="react-containers-DefinitionTooltip-0" href="/docs/ja-jp/glossary?term=auth0-dashboard" tip="Auth0 Dashboard: サービスを構成するためのAuth0の主製品。" cta="用語集の表示">Auth0 Dashboard</Tooltip>を使用して構成できます。

## cross-origin認証を構成する

1. [［Dashboard］>［Applications（アプリケーション）］>［Applications（アプリケーション）］](https://manage.auth0.com/#/applications)の順に移動し、アプリケーションの名前をクリックして表示します。
2. **［Cross-Origin Authentication（Cross-Origin認証）］** で、**［Allow Cross-Origin Authentication（Cross-Origin認証を許可する）］** をオンに切り替えます。
3. **［Allowed Origins (CORS)（許可されているオリジン（CORS））］** に、アプリケーションのオリジンURLを入力します。オリジンについての詳細は、[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（cross-origin認証を許可する）］** が無効であることを確認してください。
</Callout>

## cross-origin検証ページを作成する

状況によっては、サードパーティのクッキーを利用できない場合があります。特定のバージョンのブラウザーではサードパーティのクッキーがサポートされておらず、仮にサポートされていても、ユーザーの設定で無効にされている場合があります。

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

Chrome、Opera、Safariなど、サポートされていないブラウザーでは、サードパーティのクッキーが無効になっている場合、[カスタムドメイン](/docs/ja-jp/customize/custom-domains)を有効にしない限り、cross-origin認証は機能しません。

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  **Safari** の構成では、「サイト越えトラッキングを防ぐ」設定として[インテリジェントトラッキング防止機能](https://webkit.org/blog/7675/intelligent-tracking-prevention/)が使用されています。その結果、残念ながら認証にサードパーティクッキーを役立てることもできなくなります。ここで、[トークンの更新](https://auth0.com/docs/api-auth/token-renewal-in-safari)に及ぶ影響の一例をご紹介します。
</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" lines />

サードパーティのクッキーが利用できない場合、Auth0.jsは異なるcross-origin検証フローを呼び出すためにiframeをレンダリングします。
2\. [［Dashboard］>［Applications（アプリケーション）］>［Applications（アプリケーション）］](https://manage.auth0.com/#/applications)の順に移動し、アプリケーションを選択して表示します。
3\. **［Cross-Origin Authentication（Cross-Origin認証）］** で、作成したコールバックページのURLを「**Cross-Origin Verification Fallback URL（Cross-Origin検証URL）** 」フィールドに追加します。

<Warning>
  運用環境では、ページのURLが`localhost`をポイントしていないことを確認してください。ページは埋め込みログインフォームがホストされているのと同じドメイン内にあり、`https`スキーマのURL形式でなくてはなりません。
</Warning>

4. **［Save Changes（変更を保存）］** をクリックします。

詳細については、[GitHubのcross-origin認証サンプル](https://github.com/auth0/lock/blob/master/support/callback-cross-auth.html)をご覧ください。

## エラーコードと説明

<Warning>
  エラーの説明は、人間が判読できるように書かれています。いつでも変更される可能性があり、コードで解析することはできません。
</Warning>

Auth0.js v9（およびLock）が埋め込みログインに使用されると、`/co/authenticate`エンドポイントが呼び出され、以下のエラーが発生します。

| ステータス | コード                           | 説明                                                                             |
| ----- | ----------------------------- | ------------------------------------------------------------------------------ |
| `400` | `invalid_request`             | 無効な要求本文。client\_id、credential\_type、username、otp、realmのすべてが必要で、これ以外があってはなりません。 |
| `400` | `unsupported_credential_type` | 不明な資格情報タイプのパラメーター。                                                             |
| `400` | `invalid_request`             | 不明な領域の存在しない接続。                                                                 |
| `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.`（オリジンの[https://test.appは許可されていません）](https://test.appは許可されていません）)

## ブラウザーテストのサポート

以下のブラウザーでは、サードパーティのクッキーが無効になっている場合でもcross-origin認証を使用できます。

* Microsoft Internet Explorer

<Card title="SameSiteクッキー属性">
  これまで、[`samesite`](https://auth0.com/docs/sessions/concepts/cookie-attributes)[クッキー属性](https://auth0.com/docs/sessions/concepts/cookie-attributes)には`true`、`false`、`strict`、`lax`のオプションがありました。属性が手動で設定されていない場合、Auth0はデフォルト値の`false`を使用していました。

  2020年2月より、Google Chrome v80によるクッキーの取り扱いが変更され、Auth0はこれを受けて以下の変更を行いました。

  * `samesite`属性のないクッキーには`lax`が設定されます。
  * `sameSite=none`のクッキーにはセキュリティ保護が必要です。保護されていない場合、ブラウザーのcookie jarには保存できません。

  これらの変更はセキュリティを強化し、クロスサイトリクエストフォージェリ（CSRF）攻撃からの防御を目的にしています。
</Card>

## もっと詳しく

* [埋め込みログイン](/docs/ja-jp/authenticate/login/embedded-login)
* [Cross-Origin認証](/docs/ja-jp/authenticate/login/cross-origin-authentication)
* [［Application Settings（アプリケーションの設定）］](/docs/ja-jp/get-started/applications/application-settings)
* [sameSiteクッキー属性の変更](/docs/ja-jp/manage-users/cookies/samesite-cookie-attribute-changes)
