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

# アクセストークンを使用するManagement APIエンドポイントに移行する

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

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 data-tooltip-id="react-containers-DefinitionTooltip-0" href="/docs/ja-jp/glossary?term=management-api" tip="Management API: 顧客が管理タスクを実行できるようにするための製品。" cta="用語集の表示">Management API</Tooltip>エンドポイントの呼び出しにIDトークンを使用することは非推奨となります。今後はアクセストークンを使用しなければなりません。この移行の猶予期間は、**2018年3月31日** に開始しました。

アクセストークンへの移行が完了したら、Dashboardで **［Allow <Tooltip data-tooltip-id="react-containers-DefinitionTooltip-1" href="/docs/ja-jp/glossary?term=id-token" tip="IDトークン: リソースにアクセスするためのものではなく、クライアント自体を対象とした資格情報。" cta="用語集の表示">ID Tokens</Tooltip> for Management API v2 Authentication（Management API v2認証にIDトークンを許可する）］** を無効にします。

以下のいずれかのエンドポイントを呼び出すためにIDトークンを使用する場合、この移行による影響を受けます。これらのエンドポイントは、通常のアクセストークンを受け入れられるようになりました。エンドポイントの動作にその他の変更はありません。要求と応答のスキーマは同じままで、認可に使用するトークンの更新だけが必要です。

## 影響を受けるエンドポイント

| エンドポイント                                                   | ユースケース                         |
| --------------------------------------------------------- | ------------------------------ |
| 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                         | さまざまなIDプロバイダーからユーザーアカウントをリンクする |
| DELETE /api/v2/users/{id}/identities/{provider}/{user_id} | ユーザーアカウントのリンクを解除する             |

## アクション

### スコープの変更

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` |

### アクセストークンの取得

Auth0は、前述のエンドポイントについてトークンを取得する方法を変更しました。ユーザーの認証とトークンの取得方法にはいくつか種類があり、認証に使用するテクノロジーと<Tooltip data-tooltip-id="react-containers-DefinitionTooltip-1" href="/docs/ja-jp/glossary?term=oath2" tip="OAuth 2.0: 認可プロトコルとワークフローを定義する認可フレームワーク。" cta="用語集の表示">OAuth 2.0</Tooltip>フローによって異なります。

* **ブラウザーで動作するSPA** ：認可エンドポイントを使用する。
* **サーバー、モバイルアプリ、サーバープロセスまたは信頼性の高いアプリで動作するWebアプリ** ：トークンエンドポイントを使用する。
* **クロス認証** ：異なるドメインから要求が来る場合、ユーザー認証には埋め込みのロックまたはauth0.jsを使用する。

#### 認可エンドポイント

このセクションでは、認可エンドポイントでトークンを取得する方法の違いについて例を用いて説明します。どのエンドポイントを移行したいかに関わらず変更点は同じで、唯一異なる点は要求で指定するスコープです。

以下の例では、`GET User by ID`エンドポイントを使用して、ログインユーザーの完全なプロファイル情報を取得します。そのために、まず、暗黙的付与を使用してユーザーを認証し、トークンを取得します。以下は、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="javascript" />

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

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="javascript" />

Management APIにアクセスできるアクセストークンを取得するには以下を行います。

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

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

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="javascript" />

`aud`はテナントのAPI URI、`スコープ`は`${scope}`、`sub`はログインユーザーのユーザーIDに設定されています。

アクセストークンを取得したら、それを使ってエンドポイントを呼び出します。この部分は同じで、要求のうち、`Bearer`トークンとして使用する値を除き変更はありません。応答も同じです。

#### トークンエンドポイント

このセクションでは、トークンエンドポイントでトークンを取得する方法の違いについて例を用いて説明します。どのエンドポイントを移行したいかに関わらず変更点は同じで、唯一異なる点は要求で指定するスコープです。

以下の例では、`GET User by ID`エンドポイントを使用して、ログインユーザーの完全なプロファイル情報を取得します。まず、パスワード交換の付与タイプを使ってユーザーを認証してから、トークンを取得します。以下は、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="javascript" />

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

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="javascript" />

Management APIにアクセスできるアクセストークンを取得するには以下を行います。

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

アクセストークンを取得したら、それを使ってエンドポイントを呼び出します。この部分は同じで、要求のうち、`Bearer`トークンとして使用する値を除き変更はありません。応答も同じです。

#### 埋め込みのロックまたはauth0.js

アプリケーションにロックまたはauth0.js v9を埋め込んだ場合、クロスオリジン認証を使用しています。これは、異なるドメインから要求が来る場合、ユーザーの認証に使用します。

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

以下の例は、以前の方法です。

export const codeExample6 = `// get an ID Token
    var webAuth = new auth0.WebAuth({
      clientID: '{yourClientId}',
      domain: '{yourDomain}',
      redirectUri: 'https://{yourApp}/callback',
      scope: 'openid',
      responseType: 'id_token'
    });
    // create a new instance
    var auth0Manage = new auth0.Management({
      domain: '{yourDomain}',
      token: '{yourIdToken}'
    });`;

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

この例は、新しい方法です。

export const codeExample7 = `// get an Access Token
    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'
    });
    // create a new instance
    var auth0Manage = new auth0.Management({
      domain: '{yourDomain}',
      token: '{yourMgmtApiAccessToken}'
    });`;

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

* 応答でIDトークンとアクセストークンの両方を要求する

  `responseType:'token id_token'`
* Management APIを意図したトークンのオーディエンスとして設定する

  `audience:'https://YOUR_DOMAIN/api/v2/'`
* 必要なアクセス許可を要求する

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

### アカウントリンクの変更

この機能性の変更点は以下の通りです。

* `Authorization`ヘッダーにIDトークンを使用することはできなくなりました。
* `Authorization`ヘッダーでアクセストークンを使用し、付与されたアクセス許可が`update:users`の場合、要求のボディにはセカンダリアカウントの`user_id`またはIDトークンのいずれかを送信できます。
* `Authorization`ヘッダーでアクセストークンを使用し、付与されたアクセス許可が`update:current_user_metadata`の場合、要求のボディにはセカンダリアカウントのIDトークンのみ送信できます。次のような条件があります。

  * IDトークンは`RS256`を使用して署名される必要があります（この値は、**［Dashboard］>［Applications（アプリケーション）］>［Application Settings（アプリケーションの設定）］>［Advanced Settings（高度な設定）］>［OAuth］** から設定できます）
  * IDトークンの`aud`クレームは、アプリケーションを特定し、アクセストークンの`azp`クレームと同じ値でなければいけません。

## 制限

Management APIにアクセスするために使用されるアクセストークンは、`aud`クレームの値が1つのみである必要があります。トークンに複数の値がある場合、Management APIへの要求はエラーになります。

## もっと詳しく

* [アカウントリンクに向けてアクセストークンに移行する](/docs/ja-jp/troubleshoot/product-lifecycle/past-migrations/link-user-accounts-with-access-tokens-migration)
