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

> Hooks を使用して、Client Credentials フローで取得するアクセストークンのスコープを変更し、カスタムクレームを追加する方法を学びます。

# Hooks を使用して Client Credentials フローのトークンをカスタマイズする

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

<Warning>
  Rules と Hooks のサポート終了 (EOL) 日は **2026年11月18日** です。**2023年10月16日** 以降に作成された新規テナントでは、これらはすでに利用できません。既存のテナントでアクティブな Hooks がある場合は、サポート終了日まで Hooks へのアクセスが維持されます。

  Auth0 を拡張するには、Actions の使用を強く推奨します。Actions では、豊富な型情報、インラインドキュメント、公開 `npm` パッケージを利用でき、拡張機能の活用体験を向上させる外部統合にも接続できます。Actions の機能の詳細については、[Understand How Auth0 Actions Work](/ja/docs/customize/actions/actions-overview) を参照してください。

  移行を支援するために、[Rules から Actions への移行](/ja/docs/customize/actions/migrate/migrate-from-rules-to-actions) と [Hooks から Actions への移行](/ja/docs/customize/actions/migrate/migrate-from-hooks-to-actions) のガイドを用意しています。また、機能比較、[Actions のデモ](https://www.youtube.com/watch?v=UesFSY1klrI)、および移行に役立つその他のリソースをまとめた専用の [Move to Actions](https://auth0.com/extensibility/movetoactions) ページもあります。

  Rules と Hooks の廃止の詳細については、ブログ記事 [Preparing for Rules and Hooks End of Life](https://auth0.com/blog/preparing-for-rules-and-hooks-end-of-life/) を参照してください。
</Warning>

<Warning>
  2026 年に Rules 関数と Hooks 関数を削除する予定であるため、新しい Rules または Hooks を作成する場合は、Development 環境で、Actions への移行をテストする目的に限って行ってください。

  Rules を Actions に移行する方法については、[Migrate from Rules to Actions](/ja/docs/customize/actions/migrate/migrate-from-rules-to-actions) を参照してください。Hooks を Actions に移行する方法については、[Migrate from Hooks to Actions](/ja/docs/customize/actions/migrate/migrate-from-hooks-to-actions) を参照してください。
</Warning>

[Client Credentials フロー](/ja/docs/get-started/authentication-and-authorization-flow/client-credentials-flow) を通じて発行されるトークンでは、[Hooks](/ja/docs/customize/hooks) を追加することで、スコープを変更したり、カスタムクレームを追加したりできます。

Hooks を使用すると、Node.js コードで Auth0 の動作をカスタマイズできます。Hooks は、Auth0 プラットフォームの特定の拡張ポイント (Client Credentials フローなど) に関連付けられた、安全で自己完結型の関数です。Auth0 は実行時に Hooks を呼び出して、カスタムロジックを実行します。

Hooks は、<Tooltip tip="Auth0 Dashboard: サービスを設定するための Auth0 の主要製品です。" cta="用語集を見る" href="/ja/docs/glossary?term=Auth0+Dashboard">Auth0 Dashboard</Tooltip> または <Tooltip tip="Auth0 Dashboard: サービスを設定するための Auth0 の主要製品です。" cta="用語集を見る" href="/ja/docs/glossary?term=Management+API">Management API</Tooltip> を使用して管理できます。

<Warning>
  特定の拡張ポイントに対して複数の Hook を作成できますが、各拡張ポイントで同時に有効にできる Hook は 1 つだけです。その拡張ポイントに対して後から作成した Hook は自動的に無効になるため、明示的に有効化する必要があります。有効な Hook は、すべてのアプリケーションと API に対して実行されます。
</Warning>

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

このチュートリアルを開始する前に、次の作業を行ってください。

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

  * [適切な API 権限を追加する](/ja/docs/get-started/apis/add-api-permissions)
* [M2M アプリケーションを Auth0 に登録する](/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. **Hook を作成**: トークンをカスタマイズする Hook を作成します。
2. **Hook をテスト**: Client Credentials フローを実行し、アクセストークンをデコードして、新しい Hook をテストします。

<div id="create-a-hook">
  ### Hook を作成する
</div>

この例では、次のことを行います。

* [アクセストークン](/ja/docs/secure/tokens/access-tokens) に任意のクレーム (`https://foo.com/claim`) を追加する
* 設定済みの API に権限を 1 つ追加する

トークンをカスタマイズする Hook を作成します。拡張ポイントの選択を求められたら、`Client Credentials Exchange` を選択し、エディターに次のコードを追加します。

```js lines theme={null}
module.exports = function(client, scope, audience, context, cb) {
  var access_token = {};
  access_token['https://foo.com/claim'] = 'bar';
  access_token.scope = scope;
  access_token.scope.push('extra');
  cb(null, access_token);
};
```

<Warning>
  Auth0 は、[OpenID Connect (OIDC) 仕様](https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims) で定義されている構造化されたクレーム形式でユーザープロファイル情報を返します。つまり、IDトークンまたはアクセストークンに追加するカスタムクレームは、競合が発生する可能性を避けるため、[ガイドラインと制限事項](/ja/docs/secure/tokens/json-web-tokens/create-custom-claims) に準拠する必要があります。
</Warning>

<div id="test-your-hook">
  ### フック をテストする
</div>

先ほど作成した フック をテストするには、Client Credentials Exchange を実行して <Tooltip tip="アクセストークン: API へのアクセスに使用する認可クレデンシャルで、不透明な文字列または JWT の形式をとります。" cta="用語集を見る" href="/ja/docs/glossary?term=Access+Token">アクセストークン</Tooltip> を取得し、それをデコードして内容を確認する必要があります。

<div id="get-token">
  #### トークンを取得する
</div>

トークンを取得するには、[Client Credentials Flow エンドポイント](https://auth0.com/docs/api/authentication#client-credentials-flow) に `POST` リクエストを送信します。CLIENT\_ID、CLIENT\_SECRET、API\_IDENTIFIER のプレースホルダー値は、それぞれアプリケーションの <Tooltip tip="クライアントID: Auth0 が登録済みリソースに付与する識別値です。" cta="用語集を見る" href="/ja/docs/glossary?term=Client+ID">クライアントID</Tooltip>、アプリケーションの <Tooltip tip="クライアントシークレット: クライアント（アプリケーション）が認可サーバーに対して認証を行うために使用するシークレットです。クライアントと認可サーバーのみが把握している必要があり、推測されないよう十分にランダムでなければなりません。" cta="用語集を見る" href="/ja/docs/glossary?term=Client+Secret">クライアントシークレット</Tooltip>、および API の識別子に置き換えてください。クライアントID とクライアントシークレットは [Application](https://manage.auth0.com/#/applications) の設定で、API の識別子は [API](https://manage.auth0.com/#/apis) の設定で確認できます。

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

成功すると、レスポンスには次が含まれます:

* `access_token`
* 有効期限 (秒単位、`expires_in`)
* `Bearer` に設定されたトークンタイプ (`token_type`)
* `extra` 権限 (`scope`、Hook によって追加)

```json lines theme={null}
HTTP/1.1 200 OK
Content-Type: application/json
{
  "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6Ik5ESTFNa05DTVRGQlJrVTRORVF6UXpFMk1qZEVNVVEzT1VORk5ESTVSVU5GUXpnM1FrRTFNdyJ9.eyJpc3MiOiJodHRwczovL2RlbW8tYWNjb3VudC5hdXRoMC3jb20vIiwic3ViIjoic0FRSlFpQmYxREw0c2lqSVZCb2pFRUZvcmRoa0o4WUNAY2xpZW50cyIsImF1ZCI6ImRlbW8tYWNjb3VudC5hcGkiLCJleHAiOjE0ODc3NjU8NjYsImlhdCI6MTQ4NzY3OTI2Niwic2NvcGUiOiJyZWFkOmRhdGEgZXh0cmEiLCJodHRwczovL2Zvby5jb20vY2xhaW0iOiKoPXIifQ.da-48mHY_7esfLZpvHWWL8sIH1j_2mUYAB49c-B472lCdsNFvpaLoq6OKQyhnqk9_aW_Xhfkusos3FECTrLFvf-qwQK70QtwbkbVye_IuPSTAYdQ2T-XTzGDm9Nmmy5Iwl9rNYLxVs2OoCdfpVMyda0OaI0AfHBgEdKWluTP67OOnV_dF3KpuwtK3dPKWTCo2j9VCa7X1I4h0CNuM79DHhY2wO7sL8WBej7BSNA3N2TUsp_YTWWfrvsr_vVhJf-32G7w_12ms_PNFUwj2C30ZZIPWc-uEkDztyMLdI-lu9q9TLrLdr0dOhfrtfkdeJx4pUSiHdJHf42kg7UAVK6JcA",
  "expires_in": 86400,
  "scope": "extra",
  "token_type": "Bearer"
}
```

<div id="decode-token">
  #### トークンをデコードする
</div>

アクセストークンをデコードして内容を確認する最も簡単な方法は、[JWT.io Debugger](https://jwt.io/#debugger-io) を使用することです。

アクセストークンをコピーしてエディターに貼り付けます。<Tooltip tip="JSON Web Token（JWT）: 2者間でclaimsを安全に表現するために使用される、標準的な IDトークン形式（また、多くの場合はアクセストークン形式）。" cta="用語集を表示" href="/ja/docs/glossary?term=JWT">JWT</Tooltip> は自動的にデコードされ、内容が表示されます。

**ペイロード** の最後の 2 項目は、いずれもフックによって設定されていることに注意してください。

* `"scope": "extra"`
* `"https://foo.com/claim": "bar"`

<div id="learn-more">
  ## 詳細
</div>

* [Auth0 Hooks](/ja/docs/customize/hooks)
* [Client Credentials フロー](/ja/docs/get-started/authentication-and-authorization-flow/client-credentials-flow)
* [Client Credentials フローで API を呼び出す](/ja/docs/get-started/authentication-and-authorization-flow/client-credentials-flow/call-your-api-using-the-client-credentials-flow)
