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

> Authorize エンドポイントを使用してリクエストを開始する際に、リフレッシュトークンを取得する方法について説明します。

# リフレッシュトークンを取得する

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

<Tooltip tip="リフレッシュトークン: ユーザーに再度ログインさせることなく、新しいアクセストークンを取得するために使用するトークンです。" cta="用語集を表示" href="/ja/docs/glossary?term=refresh+token">リフレッシュトークン</Tooltip>を取得するには、`/authorize` エンドポイントを介して認証リクエストを開始する際に、`offline_access` [スコープ](/ja/docs/get-started/apis/scopes) を含める必要があります。API で Offline Access を必ず有効にしてください。詳細については、[API Settings](/ja/docs/get-started/apis/api-settings) を参照してください。

たとえば、[Authorization Code Flow](/ja/docs/get-started/authentication-and-authorization-flow/authorization-code-flow) を使用している場合、認証リクエストは次のようになります。

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

リフレッシュトークンはセッションに保存されます。次に、セッションの更新が必要になった場合 (たとえば、あらかじめ設定した期間が経過した場合や、ユーザーが機密性の高い操作を実行しようとした場合) 、アプリはバックエンドでリフレッシュトークンを使用して、新しい<Tooltip tip="ID Token: リソースへのアクセスではなく、クライアント自体のための認証情報です。" cta="用語集を見る" href="/ja/docs/glossary?term=ID+token">IDトークン</Tooltip>を取得します。このとき、`grant_type=refresh_token` を指定して `/oauth/token` エンドポイントを使用します。

ユーザーの認証が正常に完了すると、アプリケーションは `redirect_uri` にリダイレクトされ、URL の一部として `code` が付与されます: `{https://yourApp/callback}?code=BPPLN3Z4qCTvSNOy`。この `code` は、`/oauth/token` エンドポイントを使用して<Tooltip tip="Access Token: API へのアクセスに使用される、認可のための認証情報です。形式は不透明な文字列または JWT です。" cta="用語集を見る" href="/ja/docs/glossary?term=access+token">アクセストークン</Tooltip>と交換できます。

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

  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>

レスポンスには、アクセストークンとリフレッシュトークンが含まれている必要があります。

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

対応する Native Client (パブリック) を使用するモバイルアプリでリフレッシュトークンを要求する場合、`client_secret` は機密アプリケーションでのみ必要なため、リクエストに含める必要はありません。

リフレッシュトークンを使うと、ユーザーは実質的に無期限で認証済みの状態を維持できるため、アプリケーションで安全に保存する必要があります。

Authorization Code Flow を使用してこれを実装する方法の詳細については、チュートリアル「[Call API Using the Authorization Code Flow](/ja/docs/get-started/authentication-and-authorization-flow/authorization-code-flow/call-your-api-using-the-authorization-code-flow)」を参照してください。他のグラントについては、「[Authentication and Authorization Flows](/ja/docs/get-started/authentication-and-authorization-flow)」を参照してください。

<div id="customize-mfa">
  ## MFA をカスタマイズする
</div>

<Warning>
  Resource Owner Password Grant、埋め込み型、またはリフレッシュトークンのフローでのカスタマイズ可能な MFA は、現在早期アクセスです。この機能を使用すると、Okta の[Master Subscription Agreement](https://www.okta.com/legal/)に記載されている該当する Free Trial 条項に同意したものとみなされます。Auth0 のリリースステージの詳細については、[Product Release Stages](/ja/docs/troubleshoot/product-lifecycle/product-release-stages)を参照してください。早期アクセスに参加するには、[Auth0 Support](https://support.auth0.com/)にお問い合わせください。
</Warning>

カスタマイズ可能な MFA を使用すると、ユーザーはアプリケーションでサポートされている認証要素の中から任意のものを選んで登録し、チャレンジできます。

`oauth/token` エンドポイントでの認証中、レスポンスでは `mfa_required` エラーが返されます。このエラーには、MFA API で使用する `mfa_token` と、認証要素の一覧を含む `mfa_requirements` パラメーターが含まれます。

```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"} //チャレンジでのみ使用可能
    ]
  }
}
```

`mfa_token` を使用して [`mfa/authenticator`](/ja/docs/api/authentication/muti-factor-authentication/list-authenticators) エンドポイントを呼び出し、ユーザーが登録済みのすべての認証要素の一覧を取得したうえで、アプリケーションがサポートするものと同じタイプを特定します。チャレンジを発行するには、対応する `authenticator_type` も取得する必要があります。

```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
  }
]
```

[`request/mfa/challenge`](/ja/docs/api/authentication/muti-factor-authentication/request-mfa-challenge) エンドポイントを呼び出して、MFA チャレンジを必須にします。

Auth0 Actions を使用すると、MFA フローをさらにカスタマイズできます。詳細については、[Actions トリガー: post-challenge - API オブジェクト](/ja/docs/customize/actions/explore-triggers/password-reset-triggers/post-challenge-trigger/post-challenge-api-object) を参照してください。

<div id="learn-more">
  ## 詳しくはこちら
</div>

* [リフレッシュトークンを使用する](/ja/docs/secure/tokens/refresh-tokens/use-refresh-tokens)
* [リフレッシュトークンを失効させる](/ja/docs/secure/tokens/refresh-tokens/revoke-refresh-tokens)
* [リフレッシュトークンローテーション](/ja/docs/secure/tokens/refresh-tokens/refresh-token-rotation)
* [リフレッシュトークンの有効期限を設定する](/ja/docs/secure/tokens/refresh-tokens/configure-refresh-token-expiration)
