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

> Décrit comment obtenir un jeton d’actualisation lorsque vous lancez une requête à l’aide de l’endpoint Authorize.

# Obtenir des jetons d’actualisation

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) + "*****MASQUÉ*****";
          }
          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>;
};

Pour obtenir un <Tooltip tip="Refresh Token : jeton utilisé pour obtenir un nouveau jeton d’accès sans obliger les utilisateurs à se connecter de nouveau." cta="Consulter le glossaire" href="/docs/fr-ca/glossary?term=refresh+token">jeton d’actualisation</Tooltip>, vous devez inclure la portée `offline_access` [scope](/docs/fr-ca/get-started/apis/scopes) lorsque vous lancez une requête d’authentification au point de terminaison `/authorize`. Assurez-vous d’activer l’accès hors ligne dans votre API. Pour en savoir plus, consultez les [paramètres de l’API](/docs/fr-ca/get-started/apis/api-settings).

Par exemple, si vous utilisez le [flux de code d’autorisation](/docs/fr-ca/get-started/authentication-and-authorization-flow/authorization-code-flow), la requête d’authentification ressemblerait à ceci :

export const codeExample1 = `https://{yourDomain}/authorize?
    audience={API_AUDIENCE}&
    scope=offline_access&
    response_type=code&
    client_id={yourClientId}&
    redirect_uri={https://yourApp/callback}&
    state={OPAQUE_VALUE}`;

<AuthCodeBlock children={codeExample1} language="http" />

Le jeton d’actualisation est stocké dans la session. Ensuite, lorsqu’une session doit être actualisée (par exemple, lorsqu’une période prédéfinie s’est écoulée ou que l’utilisateur tente d’effectuer une opération sensible), l’application utilise le jeton d’actualisation côté serveur pour obtenir un nouveau <Tooltip tip="ID Token : information d’identification destinée au client lui-même, plutôt que pour accéder à une ressource." cta="Voir le glossaire" href="/docs/fr-ca/glossary?term=ID+token">ID token</Tooltip>, au moyen du endpoint `/oauth/token` avec `grant_type=refresh_token`.

Une fois l’utilisateur authentifié avec succès, l’application sera redirigée vers le `redirect_uri`, avec un `code` dans l’URL : `{https://yourApp/callback}?code=BPPLN3Z4qCTvSNOy`. Vous pouvez échanger ce code contre un <Tooltip tip="Access Token : information d’autorisation, sous la forme d’une chaîne opaque ou d’un JWT, utilisée pour accéder à une API." cta="Voir le glossaire" href="/docs/fr-ca/glossary?term=access+token">jeton d’accès</Tooltip> au moyen du endpoint `/oauth/token`.

<AuthCodeGroup>
  ```bash cURL theme={null}
  curl --request POST \
    --url 'https://{yourDomain}/oauth/token' \
    --header 'content-type: application/x-www-form-urlencoded' \
    --data grant_type=authorization_code \
    --data 'client_id={yourClientId}' \
    --data 'client_secret={yourClientSecret}' \
    --data 'code={yourAuthorizationCode}' \
    --data 'redirect_uri={https://yourApp/callback}'
  ```

  ```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=authorization_code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&code=%7ByourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}", 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=authorization_code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&code=%7ByourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}")

  	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=authorization_code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&code=%7ByourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}")
    .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: 'authorization_code',
      client_id: '{yourClientId}',
      client_secret: '{yourClientSecret}',
      code: '{yourAuthorizationCode}',
      redirect_uri: '{https://yourApp/callback}'
    })
  };

  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=authorization_code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&code=%7ByourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}",
    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=authorization_code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&code=%7ByourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}"

  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_PEER

  request = Net::HTTP::Post.new(url)
  request["content-type"] = 'application/x-www-form-urlencoded'
  request.body = "grant_type=authorization_code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&code=%7ByourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}"

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

La réponse devrait contenir un jeton d’accès et un jeton d’actualisation.

```json lines theme={null}
{
      "access_token": "eyJz93a...k4laUWw",
      "refresh_token": "GEbRxBN...edjnXbL",
      "token_type": "Bearer"
    }
```

Si vous demandez un jeton d’actualisation pour une appli mobile à l’aide du client Native correspondant (qui est public), vous n’avez pas besoin d’envoyer le `client_secret` dans la requête, puisqu’il n’est requis que pour les applications confidentielles.

Les jetons d’actualisation doivent être stockés de façon sécuritaire par une application, puisqu’ils permettent à un utilisateur de rester authentifié pratiquement indéfiniment.

Pour en savoir plus sur la façon de mettre cela en œuvre à l’aide du flux de code d’autorisation, consultez notre tutoriel, [Call API Using the flux de code d’autorisation](/docs/fr-ca/get-started/authentication-and-authorization-flow/authorization-code-flow/call-your-api-using-the-authorization-code-flow). Pour les autres grants, consultez [Authentication and Authorization Flows](/docs/fr-ca/get-started/authentication-and-authorization-flow).

<div id="customize-mfa">
  ## Personnaliser la MFA
</div>

<Warning>
  La MFA personnalisable avec les flux Resource Owner Password Grant, Embedded ou jeton d’actualisation est en accès anticipé. En utilisant cette fonctionnalité, vous acceptez les conditions applicables de l’essai gratuit figurant dans le [Master Subscription Agreement](https://www.okta.com/legal/) d’Okta. Pour en savoir plus sur les étapes de publication d’Auth0, consultez [Product Release Stages](/docs/fr-ca/troubleshoot/product-lifecycle/product-release-stages). Pour participer à l’accès anticipé, communiquez avec [Auth0 Support](https://support.auth0.com/).
</Warning>

La MFA personnalisable permet aux utilisateurs d’inscrire les facteurs pris en charge par votre application de leur choix et de les utiliser pour répondre aux demandes de vérification.

Pendant l’authentification au point de terminaison `oauth/token`, la réponse renvoie l’erreur `mfa_required`, qui inclut le `mfa_token` à utiliser avec l’API MFA ainsi que le paramètre `mfa_requirements` contenant une liste d’authentificateurs :

```json theme={null}
{
  "error": "mfa_required",
  "error_description": "Multifactor authentication required",
  "mfa_token": "Fe26...Ha",
  "mfa_requirements": {
    "challenge": [
      { "type": "otp" },
      { "type": "push-notification" },
      { "type": "phone" },
      { "type": "recovery-code" }
      { "type": "email"} //fonctionne uniquement avec challenge
    ]
  }
}
```

Utilisez le `mfa_token` pour faire une requête au point de terminaison [`mfa/authenticator`](/docs/fr-ca/api/authentication/muti-factor-authentication/list-authenticators) afin d’obtenir la liste de tous les facteurs que l’utilisateur a configurés et de trouver celui du même type que celui pris en charge par votre application.  Vous devez aussi obtenir le `authenticator_type` correspondant pour émettre les défis :

```json theme={null}
[
  {
    "type": "recovery-code",
    "id": "recovery-code|dev_qpOkGUOxBpw6R16t",
    "authenticator_type": "recovery-code",
    "active": true
  },
  {
    "type": "otp",
    "id": "totp|dev_6NWz8awwC8brh2dN",
    "authenticator_type": "otp",
    "active": true
  }
]
```

Imposez la vérification MFA en appelant le point de terminaison [`request/mfa/challenge`](/docs/fr-ca/api/authentication/muti-factor-authentication/request-mfa-challenge).

Personnalisez davantage votre flux MFA avec Auth0 Actions. Pour en savoir plus, consultez [Déclencheurs des Actions : post-challenge - objet de l’API](/docs/fr-ca/customize/actions/explore-triggers/password-reset-triggers/post-challenge-trigger/post-challenge-api-object).

<div id="learn-more">
  ## En savoir plus
</div>

* [Utiliser les jetons d’actualisation](/docs/fr-ca/secure/tokens/refresh-tokens/use-refresh-tokens)
* [Révoquer les jetons d’actualisation](/docs/fr-ca/secure/tokens/refresh-tokens/revoke-refresh-tokens)
* [Rotation des jetons d’actualisation](/docs/fr-ca/secure/tokens/refresh-tokens/refresh-token-rotation)
* [Configurer l’expiration des jetons d’actualisation](/docs/fr-ca/secure/tokens/refresh-tokens/configure-refresh-token-expiration)
