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

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

> ユーザー認証時に認可エンドポイントを使ってアクセストークンを要求し、アプリが要求してユーザーが認めた対象オーディエンスとアクセスのスコープを含める方法を説明します。

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()) {
              processedNode = processedNode.replace(new RegExp(key, "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 [processedChildren, setProcessedChildren] = useState(children);
  useEffect(() => {
    let unsubscribe = null;
    function init() {
      unsubscribe = window.autorun(() => {
        let processedChildren = children;
        for (const [key, value] of window.rootStore.variableStore.values.entries()) {
          processedChildren = processedChildren.replace(new RegExp(key, "g"), value);
        }
        setProcessedChildren(processedChildren);
      });
    }
    if (window.rootStore) {
      init();
    } else {
      window.addEventListener("adu:storeReady", init);
    }
    return () => {
      window.removeEventListener("adu:storeReady", init);
      unsubscribe?.();
    };
  }, [children]);
  return <CodeBlock filename={filename} icon={icon} language={language} lines highlight={highlight}>
      {processedChildren}
    </CodeBlock>;
};

ユーザーを認証する際、APIにアクセスするには[アクセストークン](/docs/ja-JP/ja-jp/secure/tokens/access-tokens)を要求しなければなりません。

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  これらのAuth0ツールは、アプリケーションによるユーザーの認証を可能にします。

  * [Quickstart](/docs/ja-JP/ja-jp/quickstarts)を使うと、認証を簡単に実装できます。[ユニバーサルログイン](/docs/ja-JP/ja-jp/authenticate/login/auth0-universal-login/universal-login-vs-classic-login)やAuth0の言語・フレームワーク別SDKの使い方を説明しています。
  * [Auth0 Authentication API](/docs/ja-JP/ja-jp/api/authentication)は、自分でコードを書きたい人向けの参考文献です。まず、[使用するフロー](/docs/ja-JP/ja-jp/get-started/authentication-and-authorization-flow/which-oauth-2-0-flow-should-i-use)を決めます。そして、手順に従ってフローを実装します。
</Callout>

アクセストークンを要求するには、[トークンURL](/docs/ja-JP/ja-jp/api/authentication#client-credentials-flow)に対してPOST呼び出しを行います。

<div id="example-post-to-token-url">
  #### トークン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);
  });
  ```

  ```objc Obj-C theme={null}
  #import <Foundation/Foundation.h>

  NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" };

  NSMutableData *postData = [[NSMutableData alloc] initWithData:[@"grant_type=client_credentials" dataUsingEncoding:NSUTF8StringEncoding]];
  [postData appendData:[@"&client_id={yourClientId}" dataUsingEncoding:NSUTF8StringEncoding]];
  [postData appendData:[@"&client_secret={yourClientSecret}" dataUsingEncoding:NSUTF8StringEncoding]];
  [postData appendData:[@"&audience=YOUR_API_IDENTIFIER" dataUsingEncoding:NSUTF8StringEncoding]];

  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://{yourDomain}/oauth/token"]
                                                         cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                     timeoutInterval:10.0];
  [request setHTTPMethod:@"POST"];
  [request setAllHTTPHeaderFields:headers];
  [request setHTTPBody:postData];

  NSURLSession *session = [NSURLSession sharedSession];
  NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
                                              completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                  if (error) {
                                                      NSLog(@"%@", error);
                                                  } else {
                                                      NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
                                                      NSLog(@"%@", httpResponse);
                                                  }
                                              }];
  [dataTask resume];
  ```

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

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

  ```swift Swift theme={null}
  import Foundation

  let headers = ["content-type": "application/x-www-form-urlencoded"]

  let postData = NSMutableData(data: "grant_type=client_credentials".data(using: String.Encoding.utf8)!)
  postData.append("&client_id={yourClientId}".data(using: String.Encoding.utf8)!)
  postData.append("&client_secret={yourClientSecret}".data(using: String.Encoding.utf8)!)
  postData.append("&audience=YOUR_API_IDENTIFIER".data(using: String.Encoding.utf8)!)

  let request = NSMutableURLRequest(url: NSURL(string: "https://{yourDomain}/oauth/token")! as URL,
                                          cachePolicy: .useProtocolCachePolicy,
                                      timeoutInterval: 10.0)
  request.httpMethod = "POST"
  request.allHTTPHeaderFields = headers
  request.httpBody = postData as Data

  let session = URLSession.shared
  let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
    if (error != nil) {
      print(error)
    } else {
      let httpResponse = response as? HTTPURLResponse
      print(httpResponse)
    }
  })

  dataTask.resume()
  ```
</AuthCodeGroup>

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

<table class="table">
  <thead>
    <tr>
      <th>パラメーター名</th>
      <th>説明</th>
    </tr>
  </thead>

  <tbody>
    <tr>
      <td>`grant_type`</td>
      <td>これを"client\_credentials"に設定します。</td>
    </tr>

    <tr>
      <td>`client_id`</td>
      <td>アプリケーションのクライアントID。この値は<a href="https://manage.auth0.com/#/applications">アプリケーションの設定タブ</a>で見つけることができます。</td>
    </tr>

    <tr>
      <td>`client_secret`</td>
      <td>アプリケーションのクライアントシークレット。この値は<a href="https://manage.auth0.com/#/applications">アプリケーションの設定タブ</a>で見つけることができます。使用できるアプリケーション認証方法の詳細については、「<a href="/docs/ja-JP/ja-jp/secure/application-credentials">アプリケーション資格情報</a>」をお読みください。</td>
    </tr>

    <tr>
      <td>`audience`</td>
      <td>トークンのオーディエンス（ご利用のAPI）。これは、<a href="https://manage.auth0.com/#/apis">APIの［Settings（設定）］タブ</a>の **［Identifier（識別子）］** フィールドにあります。</td>
    </tr>

    <tr>
      <td>`organization`</td>
      <td>任意。要求に関連付けたい組織の名前または識別子です。詳細については「<a href="/docs/ja-JP/ja-jp/manage-users/organizations/organizations-for-m2m-applications">組織に対するマシンツーマシンアクセス</a>」をお読みください。</td>
    </tr>
  </tbody>
</table>

<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/ja-jp/secure/tokens/id-tokens/validate-id-tokens)」および「[アクセストークンを検証する](/docs/ja-JP/ja-jp/secure/tokens/access-tokens/validate-access-tokens)」を参照してください。
</Warning>

<div id="control-access-token-audience">
  ## アクセストークンオーディエンスをコントロールする
</div>

ユーザー認証時、アクセストークンを要求して、対象オーディエンスとアクセスのスコープを要求に入れます。アプリケーションはアクセス要求に`/authorize`エンドポイントを使います。このアクセスはアプリケーションに要求され、認証においてユーザーにも認められます。

常にデフォルトのオーディエンスを含めるようにテナントを構成できます。

<table class="table">
  <thead>
    <tr>
      <th>トークンの使用</th>
      <th>形式</th>
      <th>要求されたオーディエンス</th>
      <th>要求されたスコープ</th>
    </tr>
  </thead>

  <tbody>
    <tr>
      <td>`/userinfo`エンドポイント</td>
      <td>不透明</td>
      <td>テナント名（`{yourDomain}`）、`audience`パラメーターの値なし、渡される`audience`パラメーターなし</td>
      <td>`openid`</td>
    </tr>

    <tr>
      <td>Auth0 Management API</td>
      <td>JWT</td>
      <td>Auth0 Management API v2の識別子（`https://{tenant}.auth0.com/api/v2/`）</td>

      <td />
    </tr>

    <tr>
      <td>独自のカスタムAPI</td>
      <td>JWT</td>
      <td>Auth0 Dashboardで登録されたカスタムAPIのAPI識別子</td>

      <td />
    </tr>
  </tbody>
</table>

特定の1回のインスタンスに限り、アクセストークンに複数の対象オーディエンスを入れることができます。そのためには、カスタムAPIの署名アルゴリズムを**RS256** に設定する必要があります。詳細については、[「トークンのベストプラクティス」](/docs/ja-JP/ja-jp/secure/tokens/token-best-practices)をお読みください。

<div id="multiple-audiences">
  ### 複数オーディエンス
</div>

カスタムAPI識別子のオーディエンスと`openid`のスコープを指定した場合、アクセストークンの`aud`クレームは文字列でなく配列となり、アクセストークンはカスタムAPIと`/userinfo`エンドポイントの双方に対して有効となります。単一のカスタムAPIとAuth0の`/userinfo`エンドポイントを使う場合は、アクセストークンのオーディエンスは2つ以上となります。

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

Auth0は、トークン要求時に使ったドメインの発行者`（iss）`クレームとともにトークンを発行します。[カスタムドメイン](/docs/ja-JP/ja-jp/customize/custom-domains)ユーザーは、カスタムドメインまたはAuth0ドメインのいずれかを使えます。

たとえば、`https://login.northwind.com`というカスタムドメインを使うとします。`https://login.northwind.com/authorize`からアクセストークンを要求すると、トークンの`iss`クレームは`https://login.northwind.com/`となります。しかし、`https://northwind.auth0.com/authorize`からアクセストークンを要求すると、トークンの`iss`クレームは`https://northwind.auth0.com/`となります。

Auth0 <Tooltip data-tooltip-id="react-containers-DefinitionTooltip-0" href="/docs/ja-JP/ja-jp/glossary?term=management-api" tip="Management API: 顧客が管理タスクを実行できるようにするための製品。" cta="用語集の表示">Management API</Tooltip>の対象オーディエンスのカスタムドメインからアクセストークンを要求する場合は、カスタムドメインからAuth0 Management APIを呼び出す**必要があります** 。そうしないと、アクセストークンは無効とみなされます。

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

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

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

<div id="learn-more">
  ## もっと詳しく
</div>

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