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

> Client Credentials フローを使用して、マシン間（M2M）アプリケーションから API を呼び出す方法を説明します。

# Client Credentials フローを使用して API を呼び出す

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) + "*****マスク済み*****";
          }
          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>;
};

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  このチュートリアルでは、Client Credentials フローを使用して、マシン間 (M2M) アプリケーションから API を呼び出す方法を説明します。このフローの仕組みや、これを使用するべき理由については、[Client Credentials フロー](/ja/docs/get-started/authentication-and-authorization-flow/client-credentials-flow)を参照してください。
</Callout>

Auth0 を使用すると、アプリケーションに Client Credentials フローを簡単に実装できます。認証が正常に完了すると、アプリケーションは <Tooltip tip="アクセストークン: API へのアクセスに使用される、不透明な文字列または JWT 形式の認可クレデンシャル。" cta="用語集を表示" href="/ja/docs/glossary?term=access+token">アクセストークン</Tooltip> を取得でき、これを使用して保護された API を呼び出せます。アクセストークンの詳細については、[アクセストークン](/ja/docs/secure/tokens/access-tokens)を参照してください。

<div id="prerequisites">
  ## 前提条件
</div>

**このチュートリアルを始める前に、以下を完了してください。**

* [Auth0 に API を登録する](/ja/docs/get-started/auth0-overview/set-up-apis)

  * [適切な API 権限を追加する](/ja/docs/get-started/apis/add-api-permissions)
* [Auth0 に M2M アプリケーションを登録する](/ja/docs/get-started/auth0-overview/create-applications/machine-to-machine-apps).

  * **Application Type** で **Machine to Machine Applications** を選択します。
  * 事前に登録した API を選択します。
  * M2M アプリケーションが API を呼び出せるように認可します。

<div id="steps">
  ## 手順
</div>

1. [トークンをリクエストする](#request-tokens):
   認可済みのアプリケーションから、API のアクセストークンをリクエストします。
2. [API を呼び出す](#call-api):
   取得したアクセストークンを使用して、API を呼び出します。

任意: [サンプルのユースケースを参照する](#sample-use-cases)

<div id="request-tokens">
  ### トークンをリクエストする
</div>

API にアクセスするには、その API 用のアクセストークンをリクエストする必要があります。そのためには、[トークンURL](https://auth0.com/docs/api/authentication#client-credentials) に `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 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_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
  ```
</AuthCodeGroup>

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

| パラメーター名         | 説明                                                                                                                                                                                                           |
| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `grant_type`    | `"client_credentials"` に設定します。                                                                                                                                                                               |
| `client_id`     | アプリケーションのクライアントIDです。この値は、[アプリケーションの Settings タブ](https://manage.auth0.com/#/applications)で確認できます。                                                                                                            |
| `client_secret` | アプリケーションのクライアントシークレットです。この値は、[アプリケーションの Settings タブ](https://manage.auth0.com/#/applications)で確認できます。使用可能なアプリケーションの認証方法の詳細については、[Application Credentials](/ja/docs/secure/application-credentials)を参照してください。 |
| `audience`      | トークンのオーディエンスです。API を指定します。この値は、[API の Settings タブ](https://manage.auth0.com/#/apis)の **識別子** フィールドで確認できます。                                                                                                   |
| `organization`  | 任意です。リクエストに関連付ける組織名または識別子です。詳しくは、[組織向けマシンツーマシンアクセス](/ja/docs/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トークンを検証する](/ja/docs/secure/tokens/id-tokens/validate-id-tokens)および[アクセストークンを検証する](/ja/docs/secure/tokens/access-tokens/validate-access-tokens)を参照してください。
</Warning>

<div id="call-api">
  ### API を呼び出す
</div>

M2M アプリケーションから API を呼び出すには、アプリケーションが取得したアクセストークンを Bearer トークンとして HTTP リクエストの Authorization ヘッダーに渡す必要があります。

<AuthCodeGroup>
  ```bash cURL lines theme={null}
  curl --request GET \
    --url https://myapi.com/api \
    --header 'authorization: Bearer ACCESS_TOKEN' \
    --header 'content-type: application/json'
  ```

  ```csharp C# lines theme={null}
  var client = new RestClient("https://myapi.com/api");
  var request = new RestRequest(Method.GET);
  request.AddHeader("content-type", "application/json");
  request.AddHeader("authorization", "Bearer ACCESS_TOKEN");
  IRestResponse response = client.Execute(request);
  ```

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

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

  func main() {

  	url := "https://myapi.com/api"

  	req, _ := http.NewRequest("GET", url, nil)

  	req.Header.Add("content-type", "application/json")
  	req.Header.Add("authorization", "Bearer ACCESS_TOKEN")

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

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

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

  }
  ```

  ```java Java lines theme={null}
  HttpResponse response = Unirest.get("https://myapi.com/api")
    .header("content-type", "application/json")
    .header("authorization", "Bearer ACCESS_TOKEN")
    .asString();
  ```

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

  var options = {
    method: 'GET',
    url: 'https://myapi.com/api',
    headers: {'content-type': 'application/json', authorization: 'Bearer ACCESS_TOKEN'}
  };

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

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

  curl_setopt_array($curl, [
    CURLOPT_URL => "https://myapi.com/api",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "GET",
    CURLOPT_HTTPHEADER => [
      "authorization: Bearer ACCESS_TOKEN",
      "content-type: application/json"
    ],
  ]);

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

  curl_close($curl);

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

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

  conn = http.client.HTTPSConnection("myapi.com")

  headers = {
      'content-type': "application/json",
      'authorization': "Bearer ACCESS_TOKEN"
      }

  conn.request("GET", "/api", headers=headers)

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

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

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

  url = URI("https://myapi.com/api")

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

  request = Net::HTTP::Get.new(url)
  request["content-type"] = 'application/json'
  request["authorization"] = 'Bearer ACCESS_TOKEN'

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

<div id="sample-use-cases">
  ### 使用例
</div>

<div id="customize-tokens">
  #### トークンをカスタマイズする
</div>

[Actions](/ja/docs/customize/actions) を使用すると、カスタムロジックに基づいてアクセストークンの発行を拒否したり、アクセストークンにクレームを追加したりできます。Auth0 は、クライアントクレデンシャルグラントに関連付けられた Actions を実行時に呼び出し、カスタムロジックを実行します。

詳細については、Actions の [マシン間フロー](/ja/docs/customize/actions/explore-triggers/machine-to-machine-trigger) を参照してください。

<div id="view-sample-application-server-client-api">
  #### サンプルアプリケーションを確認する: サーバークライアント + API
</div>

実装例については、アーキテクチャシナリオの [Server Client + API](/ja/docs/get-started/architecture-scenarios/server-application-api) を参照してください。このチュートリアルシリーズには、[GitHub で参照できるコードサンプル](https://github.com/auth0-samples/auth0-pnp-exampleco-timesheets)も用意されています。

API がアクセストークンを含むリクエストを受信したら、そのトークンを検証する必要があります。詳細については、[アクセストークンを検証する](/ja/docs/secure/tokens/access-tokens/validate-access-tokens) を参照してください。

<div id="learn-more">
  ## さらに詳しく
</div>

* [マシン間トリガー](/ja/docs/customize/actions/explore-triggers/machine-to-machine-trigger)
* [OpenID Connectプロトコル](/ja/docs/authenticate/protocols/openid-connect-protocol)
* [トークン](/ja/docs/secure/tokens)
