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

> Management API の資格情報として ID トークンを使用することの非推奨化と、アクセストークンを使用するように設定を移行する方法について説明します。

# アクセストークンを使用する Management 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>;
};

<Tooltip tip="ID トークン: リソースへのアクセスではなく、クライアント自体のための資格情報です。" cta="用語集を見る" href="/docs/ja-jp/glossary?term=ID+tokens">ID トークン</Tooltip>を使用して<Tooltip tip="ID トークン: リソースへのアクセスではなく、クライアント自体のための資格情報です。" cta="用語集を見る" href="/docs/ja-jp/glossary?term=Management+API">Management API</Tooltip>のエンドポイントを呼び出すことは、非推奨となります。<Tooltip tip="Management API: 顧客が管理タスクを実行できるようにする製品です。" cta="用語集を見る" href="/docs/ja-jp/glossary?term=access+tokens">アクセストークン</Tooltip>を使用する必要があります。この移行の猶予期間は**2018年3月31日**に開始されました。

アクセストークンへの移行が完了したら、Auth0 Dashboard で **Allow ID Tokens for Management API v2 Authentication** トグルをオフにしてください。

次のいずれかのエンドポイントの呼び出しに ID トークンを使用している場合は、この移行の対象となります。これらのエンドポイントでは現在、通常のアクセストークンを受け付けます。エンドポイントの動作にそれ以外の変更はありません。リクエストとレスポンスのスキーマはこれまでと同じで、認可に使用するトークンを更新するだけで済みます。

<div id="endpoints-affected">
  ## 影響を受けるエンドポイント
</div>

| エンドポイント                                                   | ユースケース                            |
| --------------------------------------------------------- | --------------------------------- |
| GET /api/v2/users/{id}                                    | ユーザー情報を取得                         |
| GET /api/v2/users/{id}/enrollments                        | ユーザーの Guardian MFA 登録情報をすべて取得     |
| PATCH /api/v2/users/{id}                                  | ユーザー情報を更新                         |
| DELETE /api/v2/users/{id}/multifactor/{provider}          | ユーザーの MFA プロバイダー設定を削除             |
| POST /api/v2/device-credentials                           | デバイスの公開鍵を作成                       |
| DELETE /api/v2/device-credentials/{id}                    | デバイス資格情報を削除                       |
| POST/api/v2/users/{id}/identities                         | さまざまなアイデンティティプロバイダーのユーザーアカウントをリンク |
| DELETE /api/v2/users/{id}/identities/{provider}/{user_id} | ユーザーアカウントのリンク解除                   |

<div id="actions">
  ## Actions
</div>

<div id="scope-changes">
  ### スコープの変更
</div>

Management API で実行できる操作は、アクセストークンに含まれるスコープによって異なります。この移行により、現在ログイン中のユーザーのデータのみを更新できる制限付きのアクセストークン、または任意のユーザーのデータを更新できるアクセストークンのいずれかを取得できます。次の表では、ケースごと、エンドポイントごとに、トークンに必要なスコープを確認できます。

たとえば、`read:users` スコープを含むアクセストークンを取得した場合、`GET /api/v2/users/{id}` エンドポイントを使って任意のユーザーのデータを取得できます。一方、トークンに `read:current_user` スコープが含まれている場合は、現在ログイン中のユーザー (そのトークンの発行対象ユーザー) の情報のみを取得できます。

| エンドポイント                                                   | 現在のユーザー用スコープ                             | 任意のユーザー用スコープ                |
| --------------------------------------------------------- | ---------------------------------------- | --------------------------- |
| GET /api/v2/users/{id}                                    | `read:current_user`                      | `read:users`                |
| GET /api/v2/users/{id}/enrollments                        | `read:current_user`                      | `read:users`                |
| POST/api/v2/users/{id}/identities                         | `update:current_user_identities`         | `update:users`              |
| DELETE /api/v2/users/{id}/identities/{provider}/{user_id} | `update:current_user_identities`         | `update:users`              |
| PATCH /api/v2/users/{id}                                  | `update:current_user_metadata`           | `update:users`              |
| PATCH /api/v2/users/{id}                                  | `create:current_user_metadata`           | `update:users`              |
| DELETE /api/v2/users/{id}/multifactor/{provider}          | `delete:current_user_metadata`           | `update:users`              |
| POST /api/v2/device-credentials                           | `create:current_user_device_credentials` | `create:device_credentials` |
| DELETE /api/v2/device-credentials/{id}                    | `delete:current_user_device_credentials` | `delete:device_credentials` |

<div id="get-access-tokens">
  ### アクセストークンを取得する
</div>

Auth0では、前述のエンドポイント向けにトークンを取得する方法が変更されました。ユーザーを認証してトークンを取得する方法は、使用する技術や、認証に用いる<Tooltip tip="OAuth 2.0: 認可プロトコルとワークフローを定義する認可フレームワーク。" cta="用語集を見る" href="/docs/ja-jp/glossary?term=OAuth+2.0">OAuth 2.0</Tooltip>のフローによって、いくつかのバリエーションがあります。

* **ブラウザーで実行されるSPA**: 認可エンドポイントを使用します。
* **サーバー上で実行されるWebアプリ、モバイルアプリ、サーバープロセス、または高い信頼性を持つアプリ**: <Tooltip tip="トークンエンドポイント: 認可サーバー上で、プログラムからトークンをリクエストするために使用されるエンドポイント。" cta="用語集を見る" href="/docs/ja-jp/glossary?term=Token+endpoint">トークンエンドポイント</Tooltip>を使用します。
* **クロス認証**: リクエストが異なるドメインから送信される場合は、embedded Lock または auth0.js を使用してユーザーを認証します。

<div id="authorization-endpoint">
  #### 認可エンドポイント
</div>

このセクションでは、認可エンドポイントでトークンを取得する方法の違いを、例を使って説明します。移行するエンドポイントがどれであっても変更内容は同じで、異なるのはリクエストで指定するスコープだけであることに注意してください。

以下の例では、`GET User by ID` エンドポイントを使用して、ログイン中のユーザーの完全なプロファイル情報を取得します。そのために、まず Implicit グラントを使用してユーザーを認証し、トークンを取得します。以下は、ID トークンを取得してそれを使ってエンドポイントを呼び出す、従来の方法の実装例です。

export const codeExample1 = `https://{yourDomain}/authorize?
      scope=openid
      &response_type=id_token
      &client_id={yourClientId}
      &redirect_uri=https://{yourApp}/callback
      &nonce={nonce}
      &state={opaqueValue}`;

<AuthCodeBlock children={codeExample1} language="http" />

以下の例では、アクセストークンを取得する新しい方法を確認できます。

export const codeExample2 = `https://{yourDomain}/authorize?
      audience=https://{yourDomain}/api/v2/
      &scope=read:current_user
      &response_type=token%20id_token
      &client_id={yourClientId}
      &redirect_uri=https://{yourApp}/callback
      &nonce={nonce}
      &state={opaqueValue}`;

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

Management API にアクセスできるアクセストークンを取得するには:

* `audience` を `https://{yourDomain}/api/v2/` に設定します
* `scope` として `${scope}` を要求します
* Auth0 が ID トークンとアクセストークンの両方を返すように、`response_type` を `id_token token` に設定します

受け取ったアクセストークンをデコードして内容を確認すると、次のようになります:

export const codeExample3 = `{
      "iss": "https://{yourDomain}/",
      "sub": "auth0|5a620d29a840170a9ef43672",
      "aud": "https://{yourDomain}/api/v2/",
      "iat": 1521031317,
      "exp": 1521038517,
      "azp": "{yourClientId}",
      "scope": "\${scope}"
    }`;

<AuthCodeBlock children={codeExample3} language="json" />

`aud` には tenant の API URI、`scope` には `${scope}`、`sub` にはログイン中のユーザー ID が設定されていることに注目してください。

アクセストークン を取得したら、それを使ってエンドポイント を呼び出せます。この部分は変わらず、request で変わるのは `Bearer` token として使用する値だけです。response も同じです。

<div id="token-endpoint">
  #### トークンエンドポイント
</div>

このセクションでは、トークンエンドポイントを使ってトークンを取得する際の違いを、例を用いて説明します。ただし、どのエンドポイントを移行する場合でも変更内容は同じで、異なるのはリクエストで指定するスコープだけであることに注意してください。

以下の例では、ログイン中のユーザーの完全なプロファイル情報を取得するために、`GET User by ID` エンドポイントを使用します。まず、Password Exchange グラントを使ってユーザーを認証し、その後トークンを取得します。以下は、ID トークンを取得し (その後、それを使ってエンドポイントを呼び出す) 従来のアプローチの実装例です。

export const codeExample4 = `POST https://{yourDomain}/oauth/token
    Content-Type: application/x-www-form-urlencoded
    {
      "grant_type": "password",
      "username": "{yourUsername}",
      "password": "{yourPassword}",
      "scope": "openid",
      "client_id": "{yourClientId}",
      "client_secret": "{yourClientSecret}",
    }`;

<AuthCodeBlock children={codeExample4} language="json" />

以下の例では、アクセストークンも取得する新しい方法を確認できます。

export const codeExample5 = `POST https://{yourDomain}/oauth/token
    Content-Type: application/x-www-form-urlencoded
    {
      "grant_type": "password",
      "username": "{yourUsername}",
      "password": "{yourPassword}",
      "audience": "https://{yourDomain}/api/v2/",
      "scope": "read:current_user",
      "client_id": "{yourClientId}",
      "client_secret": "{yourClientSecret}",
    }`;

<AuthCodeBlock children={codeExample5} language="json" />

Management API にアクセスできるアクセストークンを取得するには、次のようにします。

* `aud` を `https://{yourDomain}/api/v2/` に設定します
* スコープ `read:current_user` を要求します

アクセストークンを取得したら、それを使ってエンドポイントを呼び出せます。ここは変わらず、リクエストで変わるのは `Bearer` トークンとして使う値だけです。レスポンスも同じです。

<div id="embedded-lock-or-auth0js">
  #### 埋め込み Lock または auth0.js
</div>

アプリケーションに Lock または auth0.js v9 のいずれかを埋め込んでいる場合は、クロスオリジン認証を使用しています。これは、異なるドメインからリクエストが送信される際にユーザーを認証するために使用されます。

auth0.js を使用して Management API にアクセスし、ユーザーを管理している場合は、スクリプトを更新する必要があります。

以下の例では、従来の方法を確認できます。

export const codeExample6 = `// ID トークンを取得
    var webAuth = new auth0.WebAuth({
      clientID: '{yourClientId}',
      domain: '{yourDomain}',
      redirectUri: 'https://{yourApp}/callback',
      scope: 'openid',
      responseType: 'id_token'
    });
    // 新しいインスタンスを作成
    var auth0Manage = new auth0.Management({
      domain: '{yourDomain}',
      token: '{yourIdToken}'
    });`;

<AuthCodeBlock children={codeExample6} language="javascript" />

この例では、新しい方法を確認できます。

export const codeExample7 = `// アクセストークンを取得
    var webAuth = new auth0.WebAuth({
      clientID: '{yourClientId}',
      domain: '{yourDomain}',
      redirectUri: 'https://{yourApp}/callback',
      audience: 'https://{yourDomain}/api/v2/',
      scope: 'read:current_user',
      responseType: 'token id_token'
    });
    // 新しいインスタンスを生成
    var auth0Manage = new auth0.Management({
      domain: '{yourDomain}',
      token: '{yourMgmtApiAccessToken}'
    });`;

<AuthCodeBlock children={codeExample7} language="javascript" />

* レスポンスで ID トークン とアクセストークンの両方を要求します

  `responseType: 'token id_token'`
* トークンの<Tooltip tip="Audience: 発行されたトークンの audience を一意に識別する値です。トークン内では aud という名前で表され、その値には ID トークン の場合はアプリケーション（Client ID）の ID が、Access Token の場合は API（API Identifier）の ID が含まれます。" cta="用語集を見る" href="/docs/ja-jp/glossary?term=audience">audience</Tooltip>として Management API を設定します

  `audience: 'https://YOUR_DOMAIN/api/v2/'`
* 必要な権限を要求します

  `scope: 'read:current_user'`
* アクセストークンを使用して Management API で認証します

<div id="account-linking-changes">
  ### アカウントリンクの変更点
</div>

この機能に関する変更点は次のとおりです。

* `Authorization` header で ID トークンは使用できなくなりました
* `Authorization` header でアクセストークンを使用し、付与された権限が `update:users` の場合は、リクエスト本文でセカンダリアカウントの `user_id` または ID トークンのいずれかを送信できます
* `Authorization` header でアクセストークンを使用し、付与された権限が `update:current_user_metadata` の場合は、リクエスト本文でセカンダリアカウントの ID トークンのみを送信できます。この場合、次の条件を満たす必要があります。

  * ID トークンは `RS256` で署名されている必要があります (この値は **Auth0 Dashboard > アプリケーション > アプリケーション設定 > 詳細設定 > OAuth** で設定できます)
  * ID トークンの `aud` クレームはアプリケーションを識別するものであり、アクセストークンの `azp` クレームと同じ値である必要があります

<div id="restrictions">
  ## 制限
</div>

Management API へのアクセスに使用するアクセストークンでは、`aud` クレームに設定できる値は 1 つのみです。トークンに複数の値が含まれている場合、Management API へのリクエストはエラーになります。

<div id="learn-more">
  ## 詳しくはこちら
</div>

* [アカウントリンク 用アクセストークンへの移行](/docs/ja-jp/troubleshoot/product-lifecycle/past-migrations/link-user-accounts-with-access-tokens-migration)
