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

> Aprenda a configurar e implementar el token de actualización multirrecurso

# Configurar e implementar el token de actualización multirrecurso

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) + "*****ENMASCARADO*****";
          }
          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">
  ## Configurar aplicaciones para MRRT
</div>

Para usar <Tooltip tip="Token de actualización: token que se usa para obtener un nuevo Token de acceso sin obligar a los usuarios a volver a iniciar sesión." cta="Ver glosario" href="/es/docs/glossary?term=Refresh+Tokens">Tokens de actualización para múltiples recursos</Tooltip> (MRRT), configure las políticas de token de actualización de su aplicación mediante la [Management API](https://auth0.com/docs/api/management/v2/clients/patch-clients-by-id) de Auth0. Estas políticas especifican qué API y alcances puede solicitar la aplicación durante el intercambio de un token de actualización.

Puede definir políticas de MRRT en la propiedad `refresh_token.policies` de la aplicación.

| Propiedad  | Tipo             | Descripción                                                                                                                                                                  |
| ---------- | ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `audience` | string           | El [identificador](/es/docs/get-started/apis/api-settings#general-settings) de la API de Auth0 de la aplicación a la que se le permitirá usar el token de actualización.     |
| `scope`    | Array de strings | La lista de alcances permitidos al solicitar un token de acceso para la audiencia especificada. El scope debe ser igual o más limitado que los alcances definidos en la API. |

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  Las propiedades audience y scope deben corresponder a una aplicación existente en su inquilino; de lo contrario, se ignorarán silenciosamente durante el intercambio del token de actualización.
</Callout>

Para las aplicaciones existentes, realice una llamada PATCH al endpoint [Update a Client](https://auth0.com/docs/api/management/v2/clients/patch-clients-by-id). Para crear una aplicación nueva, realice una llamada POST al endpoint [Create a Client](https://auth0.com/docs/api/management/v2/clients/post-clients):

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

Respuesta de ejemplo:

```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">
  ## Implementa un token de actualización multirrecurso
</div>

Una vez que configures el token de actualización de tu aplicación con políticas de MRRT, podrás empezar a intercambiar un único token de actualización por <Tooltip tip="Token de acceso: credencial de autorización en forma de una cadena opaca o JWT, que se utiliza para acceder a una API." cta="Ver glosario" href="/es/docs/glossary?term=access+tokens">tokens de acceso</Tooltip> para varias API.
Para ello, tu aplicación debe iniciar un flujo de inicio de sesión mediante el [Flujo de código de autorización](/es/docs/get-started/authentication-and-authorization-flow/authorization-code-flow) o la [Concesión de contraseña del propietario del recurso](/es/docs/authenticate/login/oidc-conformant-authentication/oidc-adoption-rop-flow).

<div id="step-1-authenticate-and-request-a-refresh-token">
  ### Paso 1: Autentíquese y solicite un token de actualización
</div>

Para recibir un token de actualización, incluya el scope `offline_access` al iniciar la solicitud de autenticación. Para obtener más información, consulte [Obtener tokens de actualización](/es/docs/secure/tokens/refresh-tokens/get-refresh-tokens).

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  Si no recibe un token de actualización, confirme lo siguiente:

  * La API tiene habilitada la opción [Permitir acceso sin conexión](/es/docs/get-started/apis/api-settings#access-settings) en su configuración.
  * `offline_access` está incluido en el scope.
  * El `audience` usado en la solicitud coincide con una API configurada en su inquilino.
</Callout>

<div id="step-2-exchange-the-refresh-token-for-a-different-api">
  ### Paso 2: Intercambie el token de actualización por una API distinta
</div>

Una vez emitido el token de actualización, puede solicitar tokens de acceso para cualquier API y para los alcances definidos tanto en la autenticación inicial como en la política de MRRT. Por ejemplo:

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

 Para obtener más información, consulta [Uso de tokens de actualización](/es/docs/secure/tokens/refresh-tokens/use-refresh-tokens).

Si usas el SDK de Auth0 para Swift, puedes intercambiar el token de actualización con el siguiente código:

```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)")
    }
}
```

Para obtener más información, consulte [Auth0 Swift SDK](https://github.com/auth0/Auth0.swift/blob/master/EXAMPLES.md#api-credentials-ea).

Si usa el SDK de Auth0 para Android, puede intercambiar el Token de actualización con el siguiente código:

```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")
        }
    })
```

Para obtener más información, consulta [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">
  ### Paso 3: Llama a la API con el token de acceso
</div>

Usa el token de acceso para llamar a la API protegida mediante el [esquema de autorización HTTP Bearer](https://datatracker.ietf.org/doc/html/rfc6750). Para obtener más información, consulta [Usa tokens de acceso](/es/docs/secure/tokens/access-tokens/use-access-tokens).

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  Puedes decodificar el token de acceso en [jwt.io](https://jwt.io) para verificar lo siguiente:

  * El claim `aud` coincide con la API solicitada (por ejemplo, [https://billing.example.com](https://billing.example.com)).
  * El claim `scope` solo incluye valores permitidos.
</Callout>

<div id="use-multi-resource-refresh-token-with-actions">
  ## Usar el token de actualización multirrecurso con Actions
</div>

El uso de MRRT con [Actions](/es/docs/customize/actions) le permite configurar una lógica de decisión dinámica basada en las políticas de MRRT de la aplicación. Para facilitar esto, las Actions posteriores al inicio de sesión incluyen el objeto [`event.client.refresh_token.policies`](/es/docs/customize/actions/explore-triggers/signup-and-login-triggers/login-trigger/post-login-event-object), que proporciona información relevante, incluida la <Tooltip tip="Audiencia: identificador único de la audiencia de un token emitido. Se denomina aud en un token; su valor contiene el ID de una aplicación (ID de cliente) para un ID Token o de una API (Identificador de API) para un Token de acceso." cta="Ver glosario" href="/es/docs/glossary?term=audience">audiencia</Tooltip> y el scope.

Puede usar el objeto `event.client.refresh_token.policies` para evaluar la audiencia y el scope de la aplicación al emitir o intercambiar un token de actualización, y garantizar un control preciso sobre el acceso a la API y los scopes.

```js lines theme={null}
exports.onExecutePostLogin = async (event, api) => {
  // retorna la lista de APIs permitidas en el cliente
  const allowedAPIsInTheClient = event.client.refresh_token?.policies;

  if(allowedAPIsInTheClient?.some(policy => policy?.audience?.includes('https://myapi'))){
    // lógica personalizada
  }
};
```

<div id="evaluation-logic">
  #### Lógica de evaluación
</div>

MRRT actúa como una extensión de la autenticación original, no como un reemplazo. Al intercambiar un token de actualización, Auth0 evalúa la solicitud de intercambio según la siguiente lógica:

* **Si se omite el parámetro audience**, Auth0 devuelve un token de acceso con la audiencia original y cualquiera de los alcances adicionales configurados en la política de MRRT.
* **Si se especifica un nuevo parámetro audience**, Auth0 verifica que la audiencia esté incluida en la política de MRRT y devuelve un token de acceso para la nueva audiencia con sus alcances configurados.
* **Si se omite el parámetro scope**, Auth0 combina todos los alcances permitidos de la solicitud original y de la política de MRRT.
* **Si se especifica un nuevo parámetro scope**, Auth0 valida los alcances solicitados y devuelve un token de acceso con los alcances incluidos en la política de MRTT. Los alcances solicitados que sean no válidos o no estén autorizados se ignoran.
* **Si el parámetro audience es el mismo que el de la solicitud original**, Auth0 aplica la política de MRRT y devuelve un token de acceso para la audiencia con todos los alcances configurados en MRRT y los alcances de la autenticación original.

MRRT le permite ampliar el acceso del usuario a nuevas API sin emitir nuevos tokens de actualización ni requerir que el usuario vuelva a iniciar sesión.

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

Un usuario inicia sesión y solicita la siguiente audiencia y el siguiente scope:

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

La política de MRRT de la aplicación está configurada para añadir un scope adicional:

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

Un intercambio con un token de actualización que use la misma audiencia y no incluya alcances daría como resultado un token de acceso que contiene todos los alcances configurados:

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