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

> マルチリソース リフレッシュトークンの設定と実装の方法を学びます

# マルチリソース リフレッシュトークンの設定と実装

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

<div id="configure-applications-for-mrrt">
  ## MRRT 用にアプリケーションを設定する
</div>

Multi-Resource <Tooltip tip="リフレッシュトークン: ユーザーに再ログインを求めることなく、新しいアクセストークンを取得するために使用されるトークンです。" cta="用語集を見る" href="/ja/docs/glossary?term=Refresh+Tokens">リフレッシュトークン</Tooltip> (MRRT) を使用するには、Auth0 の [Management API](https://auth0.com/docs/api/management/v2/clients/patch-clients-by-id) を使用して、アプリケーションのリフレッシュトークンポリシーを設定します。これらのポリシーでは、リフレッシュトークンの交換時に、アプリケーションがリクエストを許可される API とスコープを指定します。

MRRT ポリシーは、アプリケーションの `refresh_token.policies` プロパティで定義できます。

| Property   | Type             | Description                                                                                                  |
| ---------- | ---------------- | ------------------------------------------------------------------------------------------------------------ |
| `audience` | string           | リフレッシュトークンの使用を許可するアプリケーションの Auth0 API [identifier](/ja/docs/get-started/apis/api-settings#general-settings)。 |
| `scope`    | Array of strings | 指定した audience に対するアクセストークンをリクエストする際に許可されるスコープの一覧。scope は、API で定義されているスコープと同じか、それより限定的である必要があります。             |

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  audience プロパティと scope プロパティは、テナント内の既存のアプリケーションに対応している必要があります。そうでない場合、リフレッシュトークン交換時にそれらは通知なく無視されます。
</Callout>

既存のアプリケーションの場合は、[Update a Client](https://auth0.com/docs/api/management/v2/clients/patch-clients-by-id) エンドポイントに PATCH リクエストを送信します。新しいアプリケーションを作成するには、[Create a Client](https://auth0.com/docs/api/management/v2/clients/post-clients) エンドポイントに POST リクエストを送信します。

<AuthCodeGroup>
  ```bash cURL theme={null}
  curl --request PATCH \
    --url 'https://{yourDomain}/api/v2/clients//{yourClientId}' \
    --header 'authorization: Bearer {yourMgmtApiAccessToken}' \
    --header 'content-type: application/json' \
    --data '{
    "refresh_token": {
      "expiration_type": "expiring",
      "rotation_type": "rotating",
      "token_lifetime": 31557600,
      "idle_token_lifetime": 2592000,
      "leeway": 0,
      "infinite_token_lifetime": false,
      "infinite_idle_token_lifetime": false,
      "policies": [
        {
          "audience": "https://api.example.com",
          "scope": ["read:data"]
        },
        {
          "audience": "https://billing.example.com",
          "scope": ["read:billing"]
        }
      ]
    }
  }'
  ```

  ```csharp C# theme={null}
  var client = new RestClient("https://{yourDomain}/api/v2/clients//{yourClientId}");
  var request = new RestRequest(Method.PATCH);
  request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}");
  request.AddHeader("content-type", "application/json");
  request.AddParameter("application/json", "{
    "refresh_token": {
      "expiration_type": "expiring",
      "rotation_type": "rotating",
      "token_lifetime": 31557600,
      "idle_token_lifetime": 2592000,
      "leeway": 0,
      "infinite_token_lifetime": false,
      "infinite_idle_token_lifetime": false,
      "policies": [
        {
          "audience": "https://api.example.com",
          "scope": ["read:data"]
        },
        {
          "audience": "https://billing.example.com",
          "scope": ["read:billing"]
        }
      ]
    }
  }", 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}/api/v2/clients//{yourClientId}"

  	payload := strings.NewReader("{
    "refresh_token": {
      "expiration_type": "expiring",
      "rotation_type": "rotating",
      "token_lifetime": 31557600,
      "idle_token_lifetime": 2592000,
      "leeway": 0,
      "infinite_token_lifetime": false,
      "infinite_idle_token_lifetime": false,
      "policies": [
        {
          "audience": "https://api.example.com",
          "scope": ["read:data"]
        },
        {
          "audience": "https://billing.example.com",
          "scope": ["read:billing"]
        }
      ]
    }
  }")

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

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

  	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.patch("https://{yourDomain}/api/v2/clients//{yourClientId}")
    .header("authorization", "Bearer {yourMgmtApiAccessToken}")
    .header("content-type", "application/json")
    .body("{
    "refresh_token": {
      "expiration_type": "expiring",
      "rotation_type": "rotating",
      "token_lifetime": 31557600,
      "idle_token_lifetime": 2592000,
      "leeway": 0,
      "infinite_token_lifetime": false,
      "infinite_idle_token_lifetime": false,
      "policies": [
        {
          "audience": "https://api.example.com",
          "scope": ["read:data"]
        },
        {
          "audience": "https://billing.example.com",
          "scope": ["read:billing"]
        }
      ]
    }
  }")
    .asString();
  ```

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

  var options = {
    method: 'PATCH',
    url: 'https://{yourDomain}/api/v2/clients//{yourClientId}',
    headers: {
      authorization: 'Bearer {yourMgmtApiAccessToken}',
      'content-type': 'application/json'
    },
    data: {
      refresh_token: {
        expiration_type: 'expiring',
        rotation_type: 'rotating',
        token_lifetime: 31557600,
        idle_token_lifetime: 2592000,
        leeway: 0,
        infinite_token_lifetime: false,
        infinite_idle_token_lifetime: false,
        policies: [
          {audience: 'https://api.example.com', scope: ['read:data']},
          {audience: 'https://billing.example.com', scope: ['read:billing']}
        ]
      }
    }
  };

  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}/api/v2/clients//{yourClientId}",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "PATCH",
    CURLOPT_POSTFIELDS => "{
    "refresh_token": {
      "expiration_type": "expiring",
      "rotation_type": "rotating",
      "token_lifetime": 31557600,
      "idle_token_lifetime": 2592000,
      "leeway": 0,
      "infinite_token_lifetime": false,
      "infinite_idle_token_lifetime": false,
      "policies": [
        {
          "audience": "https://api.example.com",
          "scope": ["read:data"]
        },
        {
          "audience": "https://billing.example.com",
          "scope": ["read:billing"]
        }
      ]
    }
  }",
    CURLOPT_HTTPHEADER => [
      "authorization: Bearer {yourMgmtApiAccessToken}",
      "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 theme={null}
  import http.client

  conn = http.client.HTTPSConnection("")

  payload = "{
    "refresh_token": {
      "expiration_type": "expiring",
      "rotation_type": "rotating",
      "token_lifetime": 31557600,
      "idle_token_lifetime": 2592000,
      "leeway": 0,
      "infinite_token_lifetime": false,
      "infinite_idle_token_lifetime": false,
      "policies": [
        {
          "audience": "https://api.example.com",
          "scope": ["read:data"]
        },
        {
          "audience": "https://billing.example.com",
          "scope": ["read:billing"]
        }
      ]
    }
  }"

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

  conn.request("PATCH", "/{yourDomain}/api/v2/clients//{yourClientId}", 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}/api/v2/clients//{yourClientId}")

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

  request = Net::HTTP::Patch.new(url)
  request["authorization"] = 'Bearer {yourMgmtApiAccessToken}'
  request["content-type"] = 'application/json'
  request.body = "{
    "refresh_token": {
      "expiration_type": "expiring",
      "rotation_type": "rotating",
      "token_lifetime": 31557600,
      "idle_token_lifetime": 2592000,
      "leeway": 0,
      "infinite_token_lifetime": false,
      "infinite_idle_token_lifetime": false,
      "policies": [
        {
          "audience": "https://api.example.com",
          "scope": ["read:data"]
        },
        {
          "audience": "https://billing.example.com",
          "scope": ["read:billing"]
        }
      ]
    }
  }"

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

レスポンス例:

```json lines theme={null}
{
  "client_id": "abc123xyz",
  "name": "My Native App",
  "refresh_token": {
    "rotation_type": "rotating",
    "policies": [
      {
        "audience": "https://api.example.com",
        "scope": ["read:data"]
      },
      {
        "audience": "https://billing.example.com",
        "scope": ["read:billing"]
      }
    ]
  }
}
```

<div id="implement-multi-resource-refresh-token">
  ## マルチリソース リフレッシュトークンを実装する
</div>

アプリケーションのリフレッシュトークンを MRRT ポリシーで設定すると、1 つのリフレッシュトークンを使って、複数の API 向けの <Tooltip tip="Access Token: API へのアクセスに使用される認可資格情報で、不透明な文字列または JWT の形式を取ります。" cta="用語集を表示" href="/ja/docs/glossary?term=access+tokens">アクセストークン</Tooltip> を取得できるようになります。
これを行うには、アプリケーションで [Authorization Code Flow](/ja/docs/get-started/authentication-and-authorization-flow/authorization-code-flow) または [Resource Owner Password Grant](/ja/docs/authenticate/login/oidc-conformant-authentication/oidc-adoption-rop-flow) のいずれかを使用してログインフローを開始する必要があります。

<div id="step-1-authenticate-and-request-a-refresh-token">
  ### ステップ 1: 認証し、リフレッシュトークンをリクエストする
</div>

リフレッシュトークンを受け取るには、認証リクエストを開始する際に `offline_access` スコープを含めます。詳細については、[リフレッシュトークンを取得する](/ja/docs/secure/tokens/refresh-tokens/get-refresh-tokens)を参照してください。

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  リフレッシュトークンを受け取れない場合は、次の点を確認してください。

  * API の設定で [Allow Offline Access](/ja/docs/get-started/apis/api-settings#access-settings) が有効になっていること。
  * `offline_access` がスコープに含まれていること。
  * リクエストで使用した `audience` が、テナントで設定済みの API と一致していること。
</Callout>

<div id="step-2-exchange-the-refresh-token-for-a-different-api">
  ### ステップ 2: リフレッシュトークンを別の API 用に交換する
</div>

リフレッシュトークンが発行されると、初回の認証時と MRRT ポリシーの両方で定義された任意の API およびスコープに対して、アクセストークンをリクエストできます。例:

<AuthCodeGroup>
  ```bash cURL theme={null}
  curl --request POST \
    --url 'https://{yourDomain}/oauth/token' \
    --header 'content-type: application/json' \
    --data '{
    "grant_type": "refresh_token",
    "client_id": "{yourClientId}",
    "refresh_token": "${refreshToken}",
    "audience": "https://billing.example.com",
    "scope": "read:billing write:billing"
  }'
  ```

  ```csharp C# theme={null}
  var client = new RestClient("https://{yourDomain}/oauth/token");
  var request = new RestRequest(Method.POST);
  request.AddHeader("content-type", "application/json");
  request.AddParameter("application/json", "{
    "grant_type": "refresh_token",
    "client_id": "{yourClientId}",
    "refresh_token": "${refreshToken}",
    "audience": "https://billing.example.com",
    "scope": "read:billing write:billing"
  }", 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": "refresh_token",
    "client_id": "{yourClientId}",
    "refresh_token": "${refreshToken}",
    "audience": "https://billing.example.com",
    "scope": "read:billing write:billing"
  }")

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

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

  	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/json")
    .body("{
    "grant_type": "refresh_token",
    "client_id": "{yourClientId}",
    "refresh_token": "${refreshToken}",
    "audience": "https://billing.example.com",
    "scope": "read:billing write:billing"
  }")
    .asString();
  ```

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

  var options = {
    method: 'POST',
    url: 'https://{yourDomain}/oauth/token',
    headers: {'content-type': 'application/json'},
    data: {
      grant_type: 'refresh_token',
      client_id: '{yourClientId}',
      refresh_token: '${refreshToken}',
      audience: 'https://billing.example.com',
      scope: 'read:billing write:billing'
    }
  };

  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": "refresh_token",
    "client_id": "{yourClientId}",
    "refresh_token": "${refreshToken}",
    "audience": "https://billing.example.com",
    "scope": "read:billing write:billing"
  }",
    CURLOPT_HTTPHEADER => [
      "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 theme={null}
  import http.client

  conn = http.client.HTTPSConnection("")

  payload = "{
    "grant_type": "refresh_token",
    "client_id": "{yourClientId}",
    "refresh_token": "${refreshToken}",
    "audience": "https://billing.example.com",
    "scope": "read:billing write:billing"
  }"

  headers = { 'content-type': "application/json" }

  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/json'
  request.body = "{
    "grant_type": "refresh_token",
    "client_id": "{yourClientId}",
    "refresh_token": "${refreshToken}",
    "audience": "https://billing.example.com",
    "scope": "read:billing write:billing"
  }"

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

 詳しくは、[リフレッシュトークンの使用](/ja/docs/secure/tokens/refresh-tokens/use-refresh-tokens)を参照してください。

Auth0 Swift SDK を使用している場合は、次のコードを使用してリフレッシュトークンを交換できます。

```swift lines theme={null}
credentialsManager.apiCredentials(forAudience: "https://example.com/me",
                                  scope: "create:me:authentication_methods") { result in
    switch result {
    case .success(let apiCredentials):
        print("Obtained API credentials: \(apiCredentials)")
    case .failure(let error):
        print("Failed with: \(error)")
    }
}
```

詳しくは、[Auth0 Swift SDK](https://github.com/auth0/Auth0.swift/blob/master/EXAMPLES.md#api-credentials-ea)を参照してください。

Auth0 Android SDK を使用している場合は、次のコードでリフレッシュトークンを交換できます。

```kotlin lines theme={null}
credentialsManager.getApiCredentials(
    audience = "https://example.com/me", scope = " create:me:authentication_methods",
    callback = object : Callback<APICredentials, CredentialsManagerException> {
        override fun onSuccess(result: APICredentials) {
            print("Obtained API credentials: $result")
        }
        override fun onFailure(error: CredentialsManagerException) {
            print("Failed with: $error")
        }
    })
```

詳しくは、[Auth0 Android SDK](https://github.com/auth0/Auth0.Android/blob/main/EXAMPLES.md#api-credentials-ea)を参照してください。

<div id="step-3-call-the-api-using-the-access-token">
  ### ステップ 3: アクセストークンを使用して API を呼び出す
</div>

[Bearer HTTP 認証スキーム](https://datatracker.ietf.org/doc/html/rfc6750)を使用して、アクセストークンで保護された API を呼び出します。詳細については、[アクセストークンの使用](/ja/docs/secure/tokens/access-tokens/use-access-tokens)を参照してください。

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  [jwt.io](https://jwt.io) でアクセストークンをデコードして、次の内容を確認できます。

  * `aud` クレームが、要求した API と一致していること (例: [https://billing.example.com](https://billing.example.com)) 。
  * `scope` クレームに、許可された値のみが含まれていること。
</Callout>

<div id="use-multi-resource-refresh-token-with-actions">
  ## Actions でマルチリソース リフレッシュトークンを使用する
</div>

MRRT を [Actions](/ja/docs/customize/actions) で使用すると、アプリケーションの MRRT ポリシーに基づく動的な判定を構成できます。これを可能にするため、post-login Actions には [`event.client.refresh_token.policies`](/ja/docs/customize/actions/explore-triggers/signup-and-login-triggers/login-trigger/post-login-event-object) オブジェクトが用意されており、<Tooltip tip="Audience: 発行されたトークンのオーディエンスを表す一意の識別子。トークン内では aud という名前で表され、その値には、IDトークン の場合はアプリケーション（クライアントID）の ID、アクセストークン の場合は API（API Identifier）の ID が含まれます。" cta="用語集を表示" href="/ja/docs/glossary?term=audience">オーディエンス</Tooltip> やスコープなどの関連情報が含まれます。

`event.client.refresh_token.policies` オブジェクトを使用すると、リフレッシュトークンの発行時または交換時にアプリケーションのオーディエンスとスコープを評価し、API へのアクセスとスコープを正確に制御できます。

```js lines theme={null}
exports.onExecutePostLogin = async (event, api) => {
  // クライアントで許可されているAPIのリストを取得する
  const allowedAPIsInTheClient = event.client.refresh_token?.policies;

  if(allowedAPIsInTheClient?.some(policy => policy?.audience?.includes('https://myapi'))){
    // カスタムロジック
  }
};
```

<div id="evaluation-logic">
  #### 評価ロジック
</div>

MRRT は元の認証を置き換えるものではなく、その拡張として機能します。リフレッシュトークンを交換する際、Auth0 は次のロジックに基づいて交換リクエストを評価します。

* **audience パラメーターが省略されている場合**、Auth0 は元のオーディエンスと、MRRT ポリシーで設定された追加のスコープを含むアクセストークンを返します。
* **新しい audience パラメーターが指定されている場合**、Auth0 はそのオーディエンスが MRRT ポリシーに含まれていることを確認し、設定されたスコープを持つ、その新しいオーディエンス向けのアクセストークンを返します。
* **scope パラメーターが省略されている場合**、Auth0 は元のリクエストと MRRT ポリシーで許可されているすべてのスコープを組み合わせます。
* **新しい scope パラメーターが指定されている場合**、Auth0 は要求されたスコープを検証し、MRRT ポリシーに含まれるスコープを持つアクセストークンを返します。無効なスコープや許可されていないスコープは、要求されても暗黙的に無視されます。
* **audience パラメーターが元のリクエストと同じ場合**、Auth0 は MRRT ポリシーを適用し、MRRT で設定されたすべてのスコープと元の認証時のスコープを持つ、そのオーディエンス向けのアクセストークンを返します。

MRRT を使用すると、新しいリフレッシュトークンを発行したり、ユーザーに再度ログインを求めたりすることなく、新しい API へのユーザーアクセスを拡張できます。

<div id="examples">
  #### 例
</div>

ユーザーは、次のオーディエンスとスコープを指定してログインします。

```json lines theme={null}
{
"audience": "https://api.example.com",  
"scope": "openid profile read:messages"
}
```

アプリケーションのMRRTポリシーでは、追加のスコープを付与するように設定されています。

```json lines theme={null}
{
  "audience": "https://api.example.com",
  "scope": ["write:messages"]
}
```

同じ audience を使用し、スコープを指定せずにリフレッシュトークン交換を行うと、設定済みのすべてのスコープを含むアクセストークンが取得されます。

```json lines theme={null}
{
  "aud": "https://api.example.com",
  "scope": "openid profile read:messages write:messages"
}
```
