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

> ユーザーの認証時に Authorize エンドポイントを使用してアクセストークンをリクエストする方法と、アプリが要求しユーザーが許可したアクセスの対象 audience とスコープを含める方法を学びます。

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

export const AuthCodeGroup = ({children, dropdown}) => {
  const [processedChildren, setProcessedChildren] = useState(children);
  useEffect(() => {
    let unsubscribe = null;
    function init() {
      unsubscribe = window.autorun(() => {
        const processChildren = node => {
          if (typeof node === "string") {
            let processedNode = node;
            for (const [key, value] of window.rootStore.variableStore.values.entries()) {
              const escapedKey = key.replaceAll(/[.*+?^${}()|[\]\\]/g, (String.raw)`\$&`);
              processedNode = processedNode.replaceAll(new RegExp(escapedKey, "g"), value);
            }
            return processedNode;
          } else if (Array.isArray(node)) {
            return node.map(processChildren);
          } else if (node && node.props && node.props.children) {
            return {
              ...node,
              props: {
                ...node.props,
                children: processChildren(node.props.children)
              }
            };
          }
          return node;
        };
        setProcessedChildren(processChildren(children));
      });
    }
    if (window.rootStore) {
      init();
    } else {
      window.addEventListener("adu:storeReady", init);
    }
    return () => {
      window.removeEventListener("adu:storeReady", init);
      unsubscribe?.();
    };
  }, [children]);
  return <CodeGroup dropdown={dropdown}>{processedChildren}</CodeGroup>;
};

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

API にアクセスするには、ユーザーの認証時に [アクセストークン](/docs/ja-jp/secure/tokens/access-tokens) をリクエストする必要があります。

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  これらの Auth0 ツールは、ユーザーを認証できるようにアプリケーションを変更する際に役立ちます。

  * [Quickstarts](/docs/ja-jp/quickstarts) は、認証を実装する最も簡単な方法です。[Universal Login](/docs/ja-jp/authenticate/login/auth0-universal-login/universal-login-vs-classic-login) と、Auth0 の言語別・フレームワーク別 SDK の使い方を紹介しています。
  * [Auth0 Authentication API](https://auth0.com/docs/api/authentication) は、自分でコードを書いて実装したい方向けのリファレンスです。まず、[使用するフローを特定し](/docs/ja-jp/get-started/authentication-and-authorization-flow/which-oauth-2-0-flow-should-i-use)、次にそのフローを実装するための手順に従ってください。
</Callout>

<Tooltip tip="Access Token: API へのアクセスに使用される認可資格情報で、不透明な文字列または JWT の形式を取ります。" cta="用語集を表示" href="/docs/ja-jp/glossary?term=access+token">アクセストークン</Tooltip> をリクエストするには、[token URL](https://auth0.com/docs/api/authentication#client-credentials-flow) に POST リクエストを送信します。

<div id="example-post-to-token-url">
  #### token URL に POST する例
</div>

<AuthCodeGroup>
  ```bash cURL theme={null}
  curl --request POST \
    --url 'https://{yourDomain}/oauth/token' \
    --header 'content-type: application/x-www-form-urlencoded' \
    --data grant_type=client_credentials \
    --data client_id={yourClientId} \
    --data client_secret={yourClientSecret} \
    --data audience=YOUR_API_IDENTIFIER
  ```

  ```csharp C# theme={null}
  var client = new RestClient("https://{yourDomain}/oauth/token");
  var request = new RestRequest(Method.POST);
  request.AddHeader("content-type", "application/x-www-form-urlencoded");
  request.AddParameter("application/x-www-form-urlencoded", "grant_type=client_credentials&client_id={yourClientId}&client_secret={yourClientSecret}&audience=YOUR_API_IDENTIFIER", ParameterType.RequestBody);
  IRestResponse response = client.Execute(request);
  ```

  ```go Go theme={null}
  package main

  import (
  	"fmt"
  	"strings"
  	"net/http"
  	"io/ioutil"
  )

  func main() {

  	url := "https://{yourDomain}/oauth/token"

  	payload := strings.NewReader("grant_type=client_credentials&client_id={yourClientId}&client_secret={yourClientSecret}&audience=YOUR_API_IDENTIFIER")

  	req, _ := http.NewRequest("POST", url, payload)

  	req.Header.Add("content-type", "application/x-www-form-urlencoded")

  	res, _ := http.DefaultClient.Do(req)

  	defer res.Body.Close()
  	body, _ := ioutil.ReadAll(res.Body)

  	fmt.Println(res)
  	fmt.Println(string(body))

  }
  ```

  ```java Java theme={null}
  HttpResponse<String> response = Unirest.post("https://{yourDomain}/oauth/token")
    .header("content-type", "application/x-www-form-urlencoded")
    .body("grant_type=client_credentials&client_id={yourClientId}&client_secret={yourClientSecret}&audience=YOUR_API_IDENTIFIER")
    .asString();
  ```

  ```javascript Node.JS theme={null}
  var axios = require("axios").default;

  var options = {
    method: 'POST',
    url: 'https://{yourDomain}/oauth/token',
    headers: {'content-type': 'application/x-www-form-urlencoded'},
    data: new URLSearchParams({
      grant_type: 'client_credentials',
      client_id: '{yourClientId}',
      client_secret: '{yourClientSecret}',
      audience: 'YOUR_API_IDENTIFIER'
    })
  };

  axios.request(options).then(function (response) {
    console.log(response.data);
  }).catch(function (error) {
    console.error(error);
  });
  ```

  ```php PHP theme={null}
  $curl = curl_init();

  curl_setopt_array($curl, [
    CURLOPT_URL => "https://{yourDomain}/oauth/token",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_POSTFIELDS => "grant_type=client_credentials&client_id={yourClientId}&client_secret={yourClientSecret}&audience=YOUR_API_IDENTIFIER",
    CURLOPT_HTTPHEADER => [
      "content-type: application/x-www-form-urlencoded"
    ],
  ]);

  $response = curl_exec($curl);
  $err = curl_error($curl);

  curl_close($curl);

  if ($err) {
    echo "cURL Error #:" . $err;
  } else {
    echo $response;
  }
  ```

  ```python Python theme={null}
  import http.client

  conn = http.client.HTTPSConnection("")

  payload = "grant_type=client_credentials&client_id={yourClientId}&client_secret={yourClientSecret}&audience=YOUR_API_IDENTIFIER"

  headers = { 'content-type': "application/x-www-form-urlencoded" }

  conn.request("POST", "/{yourDomain}/oauth/token", payload, headers)

  res = conn.getresponse()
  data = res.read()

  print(data.decode("utf-8"))
  ```

  ```ruby Ruby theme={null}
  require 'uri'
  require 'net/http'
  require 'openssl'

  url = URI("https://{yourDomain}/oauth/token")

  http = Net::HTTP.new(url.host, url.port)
  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL::VERIFY_PEER

  request = Net::HTTP::Post.new(url)
  request["content-type"] = 'application/x-www-form-urlencoded'
  request.body = "grant_type=client_credentials&client_id={yourClientId}&client_secret={yourClientSecret}&audience=YOUR_API_IDENTIFIER"

  response = http.request(request)
  puts response.read_body
  ```
</AuthCodeGroup>

<div id="parameters">
  ##### パラメーター
</div>

| Parameter Name  | Description                                                                                                                                                                                                |
| --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `grant_type`    | `"client_credentials"` に設定します。                                                                                                                                                                             |
| `client_id`     | アプリケーションの Client ID です。この値は、[アプリケーションの設定タブ](https://manage.auth0.com/#/applications)で確認できます。                                                                                                               |
| `client_secret` | アプリケーションの Client Secret です。この値は、[アプリケーションの設定タブ](https://manage.auth0.com/#/applications)で確認できます。使用可能なアプリケーションの認証方法について詳しくは、[Application Credentials](/docs/ja-jp/secure/application-credentials)を参照してください。 |
| `audience`      | トークンの audience です。通常は API を指定します。この値は、[API の設定タブ](https://manage.auth0.com/#/apis)の **Identifier** フィールドで確認できます。                                                                                           |
| `organization`  | 任意です。request に関連付ける組織名または識別子です。詳しくは、[Organizations の Machine-to-Machine Access](/docs/ja-jp/manage-users/organizations/organizations-for-m2m-applications)を参照してください。                                       |

<div id="response">
  #### レスポンス
</div>

`access_token`、`token_type`、`expires_in` の値を含むペイロードを含む `HTTP 200` レスポンスが返されます。

```json lines theme={null}
{
  "access_token":"eyJz93a...k4laUWw",
  "token_type":"Bearer",
  "expires_in":86400
}
```

<Warning>
  保存する前に、トークンを検証してください。方法については、[IDトークンの検証](/docs/ja-jp/secure/tokens/id-tokens/validate-id-tokens)と[アクセストークンの検証](/docs/ja-jp/secure/tokens/access-tokens/validate-access-tokens)をご覧ください。
</Warning>

<div id="control-access-token-audience">
  ## アクセストークンのaudienceを制御する
</div>

ユーザーが認証されると、アクセストークンをリクエストし、その際に対象の<Tooltip tip="Audience: 発行されたトークンのaudienceを一意に識別する識別子です。トークン内では aud という名前で表され、その値には、ID Token の場合は application（Client ID）、Access Token の場合は API（API Identifier）のいずれかの ID が含まれます。" cta="用語集を見る" href="/docs/ja-jp/glossary?term=audience">audience</Tooltip>とアクセスのスコープをrequestに含めます。アプリケーションは `/authorize` エンドポイントを使用してアクセスをリクエストします。このアクセスはアプリケーションによって要求され、認証中にユーザーによって許可されます

テナントは、常にデフォルトのaudienceが含まれるように設定できます。

| Token Use            | Format | Requested Audience                                                       | Requested Scope |
| -------------------- | ------ | ------------------------------------------------------------------------ | --------------- |
| /userinfo endpoint   | Opaque | tenant 名 (`\{yourDomain}`)、`audience` パラメーターの値なし、`audience` パラメーターも渡されない | `openid`        |
| Auth0 Management API | JWT    | Management API v2 identifier (`https://{tenant}.auth0.com/api/v2/`)      |                 |
| 独自のカスタム API          | JWT    | Auth0 Dashboard に登録されたカスタム API の API Identifier                          |                 |

アクセストークンが複数の対象audienceを持てるのは、特定の1つのケースだけです。そのためには、カスタム API の<Tooltip tip="Signing Algorithm: トークンが改ざんされていないことを保証するために、トークンへデジタル署名する際に使用するアルゴリズムです。" cta="用語集を見る" href="/docs/ja-jp/glossary?term=signing+algorithm">署名アルゴリズム</Tooltip>を**RS256**に設定する必要があります。詳しくは、[Token Best Practices](/docs/ja-jp/secure/tokens/token-best-practices)を参照してください。

<div id="multiple-audiences">
  ### 複数のaudience
</div>

カスタムAPI識別子をaudienceに、`openid`をスコープに指定すると、発行されるアクセストークンの`aud` claimは文字列ではなく配列になります。また、そのアクセストークンはカスタムAPIと`/userinfo` エンドポイントの両方に対して有効です。アクセストークンに2つ以上のaudienceを設定できるのは、単一のカスタムAPIとAuth0の`/userinfo` エンドポイントを併用する場合に限られます。

<div id="custom-domains-and-the-auth0-management-api">
  ### カスタムドメインと Auth0 Management API
</div>

Auth0 は、トークンのリクエスト時に使用したドメインに応じて、対応する issuer (`iss)` claim) を持つトークンを発行します。[カスタムドメイン](/docs/ja-jp/customize/custom-domains) のユーザーは、<Tooltip tip="Custom Domain: 特殊な、または独自の名前を持つサードパーティのドメイン。" cta="用語集を見る" href="/docs/ja-jp/glossary?term=custom+domain">カスタムドメイン</Tooltip>または Auth0 ドメインのいずれかを使用できます。

たとえば、`https://login.northwind.com` というカスタムドメインがあるとします。`https://login.northwind.com/authorize` からアクセストークンをリクエストした場合、そのトークンの `iss` claim は `https://login.northwind.com/` になります。一方、`https://northwind.auth0.com/authorize` からアクセストークンをリクエストした場合、そのトークンの `iss` claim は `https://northwind.auth0.com/` になります。

カスタムドメインから、対象 audience を Auth0 の <Tooltip tip="Management API: お客様が管理タスクを実行できるようにする製品です。" cta="用語集を見る" href="/docs/ja-jp/glossary?term=Management+API">Management API</Tooltip> に指定してアクセストークンをリクエストする場合は、Auth0 Management API も **必ず** カスタムドメイン経由で呼び出す必要があります。そうしないと、そのアクセストークンは無効と見なされます。

<div id="renew-access-tokens">
  ## アクセストークンを更新する
</div>

デフォルトでは、カスタム API のアクセストークンの有効期間は 86400 秒 (24 時間) です。[トークンの有効期限が切れるまでの時間を短くする](/docs/ja-jp/secure/tokens/access-tokens/update-access-token-lifetime)こともできます。

アクセストークンの有効期限が切れたら、アクセストークンを更新できます。その場合は、Auth0 を使用してユーザーを再認証するか、[リフレッシュトークン](/docs/ja-jp/secure/tokens/refresh-tokens)を使用します。

<div id="learn-more">
  ## 詳しく見る
</div>

* [アクセストークンを検証する](/docs/ja-jp/secure/tokens/access-tokens/validate-access-tokens)
* [アクセストークンを使用する](/docs/ja-jp/secure/tokens/access-tokens/use-access-tokens)
* [JSON Web Tokens](/docs/ja-jp/secure/tokens/json-web-tokens)
* [リフレッシュトークン](/docs/ja-jp/secure/tokens/refresh-tokens)
* [IDプロバイダーのアクセストークン](/docs/ja-jp/secure/tokens/access-tokens/identity-provider-access-tokens)
* [Management API アクセストークン](/docs/ja-jp/secure/tokens/access-tokens/management-api-access-tokens)
