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

# 本番環境向け Management API アクセストークンの取得

> Management API を定期的かつ高頻度で呼び出すためのアクセストークンを取得する方法を説明します。

本番環境で定期的に頻繁な呼び出しを行うには、自動的にトークンを取得できるプロセスをバックエンドに構築する必要があります (これにより、有効期限のないトークンを擬似的に再現できます) 。

## 前提条件

* [Machine-to-Machine アプリケーションを登録する](/docs/docs/ja-jp/get-started/auth0-overview/create-applications/machine-to-machine-apps).

## アクセストークンを取得する

Auth0 に Management API (Management API: お客様が管理タスクを実行できるようにするプロダクト。) v2 トークンをリクエストするには、事前準備の手順で作成した Machine-to-Machine Application の認証情報を使用して、`https://{yourDomain}/oauth/token` エンドポイントに `POST` リクエストを送信します。

ペイロードは次の形式にする必要があります。

`` `{yourClientSecret}` `` は、[Application の Settings タブ](https://manage.auth0.com/#/applications/\{yourClientId}/settings)にあるclient secret (Client Secret: クライアント（アプリケーション）が Authorization Server に対して認証を行うために使用する秘密情報です。クライアントと Authorization Server だけが知っているべきもので、推測されないよう十分にランダムである必要があります。)に更新してください。

リクエストパラメーターは次のとおりです。

| Request Parameter | Description |
| - | - |
| **grant\_type** | 実行する [OAuth 2.0 フロー](/docs/docs/ja-jp/authenticate/protocols/oauth#grant-types)を示します。マシン間通信では、`client_credentials` を使用します。 |
| **client\_id** | 作成した Machine-to-Machine Application の **Client ID** フィールドの値です。[Application の Settings タブ](https://manage.auth0.com/#/applications/\{yourClientId}/settings)で確認できます。 |
| **client\_secret** | 作成した Machine-to-Machine Application の **Client Secret** フィールドの値です。[Application の Settings タブ](https://manage.auth0.com/#/applications/\{yourClientId}/settings)で確認できます。 |
| **audience** | `Auth0 Management API` の **Identifier** フィールドの値です。[API の Settings タブ](https://manage.auth0.com/#/apis)で確認できます。 |

> [!WARNING]
>
> `update:client_grants` scope と `create:client_grants` scope を使用するのは、高い特権を持つアプリケーションのみにしてください。これらを使用すると、クライアントが自分自身に追加の権限を付与できるためです。

レスポンスには、[署名付き JWT](/docs/docs/ja-jp/secure/tokens/json-web-tokens)、有効期限、付与されたスコープ、トークンタイプが含まれます。

```json lines theme={null}
{
  "access_token": "eyJ...Ggg",
  "expires_in": 86400,
  "scope": "read:clients create:clients read:client_keys",
  "token_type": "Bearer"
}
```

以上から、アクセストークン (アクセストークン: API へのアクセスに使用される、不透明な文字列または JWT 形式の認可資格情報。) の有効期限は 24 時間 (86400 秒) で、アプリケーションの読み取りと作成が許可されており、[Bearer Access Token](https://tools.ietf.org/html/rfc6750) であることがわかります。

### Auth0 の Node.js クライアントライブラリを使用する

HTTP 呼び出しの代わりに、[node-auth0](https://www.npmjs.com/package/auth0) ライブラリを使用して、[Management API のトークンを自動的に取得](https://www.npmjs.com/package/auth0#user-content-management-api-client)できます。

## アクセストークンを使用する

このトークンを使用するには、リクエストの `Authorization` ヘッダーに指定します。

たとえば、[すべてのアプリケーションを取得](/docs/docs/ja-jp/api/management/v2/clients/get-clients)するには、次を使用します。

Auth0 CLI を使用していますか？まだセットアップしていない場合は、このコマンドを実行する前に[CLI セッションをセットアップして認証](/docs/docs/ja-jp/deploy-monitor/auth0-cli)してください。

各エンドポイントの curl コマンドは、Management API v2 Explorer から取得できます。呼び出したいエンドポイントに移動し、**Test this endpoint** セクションの **get curl command** リンクをクリックしてください。

## 例: Python 実装

この Python スクリプトは Management API v2 のアクセストークンを取得し、それを使って [すべてのアプリケーションを取得](/docs/docs/ja-jp/api/management/v2/clients/get-clients) エンドポイントを呼び出し、レスポンスをコンソールに出力します。

実行する前に、次の変数に有効な値が設定されていることを確認してください。

* `AUDIENCE`: `Auth0 Management API` の **Identifier**。これは [API の Settings タブ](https://manage.auth0.com/#/apis) で確認できます。
* `DOMAIN`: 作成した Machine-to-Machine Application の **Domain**。
* `CLIENT_ID`: 作成した Machine to Machine Application の **Client ID (Client ID: Auth0 から登録済みリソースに付与される識別値。)**。
* `CLIENT_SECRET`: 作成した Machine-to-Machine Application の **Client Secret**。

```python lines expandable theme={null}
def main():
  import json, requests
  from requests.exceptions import RequestException, HTTPError, URLRequired

  # 設定値
  domain = 'YOUR_DOMAIN'
  audience = f'https://{domain}/api/v2/'
  client_id = '{yourClientId}'
  client_secret = '{yourClientSecret}'
  grant_type = "client_credentials" # 使用する OAuth 2.0 フロー

  # Auth0 からアクセストークンを取得する
  base_url = f"https://{domain}"
  payload =  { 
    'grant_type': grant_type,
    'client_id': client_id,
    'client_secret': client_secret,
    'audience': audience
  }
  response = requests.post(f'{base_url}/oauth/token', data=payload)
  oauth = response.json()
  access_token = oauth.get('access_token')

  # リクエストの Authorization ヘッダーにトークンを追加する
  headers = {
    'Authorization': f'Bearer {access_token}',
    'Content-Type': 'application/json'
  }

  # トークンを使用してすべてのアプリケーションを取得する
  try:
    res = requests.get(f'{base_url}/api/v2/clients', headers=headers)
    print(res.json())
  except HTTPError as e:
    print(f'HTTPError: {str(e.code)} {str(e.reason)}')
  except URLRequired as e:
    print(f'URLRequired: {str(e.reason)}')
  except RequestException as e:
    print(f'RequestException: {e}')
  except Exception as e:
    print(f'Generic Exception: {e}')

# main() 関数を呼び出すための定型コード。
if __name__ == '__main__':
  main()
```

## 詳細はこちら

* [テスト用の Management API アクセストークン を取得する](/docs/docs/ja-jp/secure/tokens/access-tokens/management-api-access-tokens/get-management-api-access-tokens-for-testing)
* [シングルページアプリケーション向けの Management API アクセストークン を取得する](/docs/docs/ja-jp/secure/tokens/access-tokens/management-api-access-tokens/get-management-api-tokens-for-single-page-applications)
* [Auth0 のアプリケーション](/docs/docs/ja-jp/get-started/applications)
