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

# Authentication APIで組織名を使用する

> Authentication APIで組織名を使用する際のセットアップ、セキュリティへの配慮、およびベストプラクティスについて説明します。

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

デフォルトで、[Authentication API](https://auth0.com/docs/api/authentication)は組織IDを使用して特定の組織を識別します。必要であれば、テナントでも組織名が識別子として使われるように構成することができます。ただし、この機能を有効にする前に、使いやすさやセキュリティへの影響を考慮する必要があります。潜在的な影響を明確に理解するために、「[考慮と推薦事項](#considerations-and-recommendations)」セクションを確認してください。

## 仕組み

Authentication APIで組織名に対応するようにテナントを構成すると、それに付随して以下が起こります。

* `organization` パラメーターは[/authorize](https://auth0.com/docs/api/authentication#authorize-application)と[SAML](https://auth0.com/docs/api/authentication#saml)エンドポイントで組織名と組織IDの両方を受け付けることができます。
* アクセストークンとIDトークンには自動的に`org_name`と`org_id`クレームが含まれます。

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  - [Organizations](/docs/ja-jp/manage-users/organizations/configure-organizations/create-organizations)は、2つの名前で構成できます。1つは、一意の論理識別子の役割を果たす必須の名前値で、もう1つは、任意で設定できる、わかりやすい表示名です。`org_name` パラメーターは、必須の名前値のみを受け入れ、表示名値には対応していません。
  - この機能はテナントレベルで管理されます。特定のOrganizationに対して個別に有効化することはできません。
</Callout>

この機能は、<Tooltip data-tooltip-id="react-containers-DefinitionTooltip-0" href="/docs/ja-jp/glossary?term=auth0-dashboard" tip="Auth0 Dashboard: サービスを構成するためのAuth0の主製品。" cta="用語集の表示">Auth0 Dashboard</Tooltip>または<Tooltip data-tooltip-id="react-containers-DefinitionTooltip-0" href="/docs/ja-jp/glossary?term=management-api" tip="Management API: 顧客が管理タスクを実行できるようにするための製品。" cta="用語集の表示">Management API</Tooltip>で有効にすることができます。

* **Auth0 Dashboard**：左のメニューから[［Settings（設定）］](/docs/ja-jp/get-started/tenant-settings)を選択し、**［Advanced（詳細設定）］** タブを選択します。**［Settings（設定）］** セクションで **［Allow Organization Names in Authentication API（Authentication APIで組織名を許可する）］** トグルを有効にします。
* **Management API**：`PATCH /api/v2/tenants/settings`エンドポイントを使用して、`allow_organization_name_in_authentication_api`を`true`に設定します。詳細については、[Management API](https://auth0.com/docs/api/management/v2)のドキュメントをご覧ください。

### フローの例

以下は、組織名を使った認可コードフローの例です。

1.`/authorize`エンドポイントを呼び出して、`organization`パラメーターで組織名を渡します。

export const codeExample1 = `https://{yourDomain}/authorize?
    response_type=code&
    client_id={yourClientId}&
    redirect_uri={https://yourApp/callback}&
    scope={scope}&
    state={state}&
    organization={yourOrganizationName}`;

<AuthCodeBlock children={codeExample1} language="text" lines />

2.認可コードを受け取ったら、`POST /oauth/token`エンドポイントを呼び出して、アクセストークンとIDトークンを取得します。

export const codeExample2 = `curl --request POST \
  --url 'https://{yourDomain}/oauth/token' \
  --header 'content-type: application/x-www-form-urlencoded' \
  --data grant_type=authorization_code \
  --data 'client_id={yourClientId}' \
  --data 'client_secret={yourClientSecret}' \
  --data 'code=yourAuthorizationCode}' \
  --data 'redirect_uri={https://yourApp/callback}'`;

<AuthCodeBlock children={codeExample2} language="bash" />

3.デーコードされたトークンが返され、`org_id`と`org_name`クレームの両方が含まれています。

```json lines theme={null}
{
    "sub": "google-oauth2|10...17",
    "aud": [
        "https://yourApp"
    ],
    "iat": 1686840988,
    "exp": 1686927388,
    "azp": "Suo...qTd",
    "scope": "openid profile",
    "org_id": "{yourOrganizationId}",
    "org_name": "{yourOrganizationName}"
}
```

## 考慮と推薦事項

Authentication APIで組織名を使用する前に、組織名と組織IDの違いを理解することが重要です。

全く変更されることのない組織IDと違って、組織名は最初に作成してからいつでも変更することができます。また、組織名は、一度に**1つだけ** の組織に割り当てられているのであれば、1つのテナント内で再利用することができます。つまり、実際には、テナントにある1つの組織の名前を変更すると、その元の名前をテナントにある別の組織に使用できることになります。同じ組織名が多用できないのは1つのテナント内だけです。同じ組織名を複数のテナントで使用することはできます。

一般的に、トークンの検証では組織IDの使用が推奨されます。ただし、実際の運用で組織名の方が適している場合には、機能を実装する前に、以下の影響を考慮してください。

### 使いやすさとセキュリティへの配慮

トークンの要求や認証で組織名を使用すると、潜在的に以下のような影響があることを考慮してください。

* **組織名は再利用される可能性がある** ：有効期間の長いトークンは組織名が変更されても失効しないため、トークンにあるorg\_nameクレームには以前の値が含まれたままになります。以前の組織名が別の組織によって再利用された場合、そのようなトークンは、新しい組織が管理するデータやリソースに対して、ユーザーが不正にアクセスすることを許す可能性があります。
* **1つのテナント内で同じ組織名は多用できない** ：APIが`iss`（発行者）クレームを検証しない場合、別のテナントにある同名の組織が生成したトークンを、APIが間違って受け入れてしまうかもしれません。
* **組織名は変更可能** ：組織名を変更すると、アプリケーションはAuthentication APIの要求に対して、新しい組織名を提供しなければなりません。トークンの有効期間が長いこともあるため、`org_name`クレームが現在の組織名と一致しない可能性があります。そのために、アプリケーションが適切な組織へのアクセスを拒まれる可能性があります。

### 推奨されるベストプラクティス

セキュリティや使いやすさへの影響を考慮して、組織に関してはトークンの検証に名前ではなくIDの使用をお勧めします。組織名の使用を選んだ場合には、エクスペリエンスを最適にするために、以下のベストプラクティスに従ってください。

* 必ず`iss` クレームを検証し、使用しているAuth0テナントが発行したトークンであることを確認します。
* テナントで以前に使用していた組織名を再利用することは避けます。再利用を防いで、以前に発行されたトークンが別の組織へのアクセスに使用できないことを確実にするために、過去に使用されていた組織名を正確に記録して更新します。
* 絶対的な必要性のない限り、現在使用している組織名の変更は避けます。組織名を変更することにした場合には、既存のアクセストークンやIDトークンにある組織名が自動的に新しい組織名に書き換わるわけではないことを理解してください。組織名を変更した後は、ユーザーにログインし直すよう促してください。
