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

<Tooltip tip="リフレッシュトークン: ユーザーに再度ログインを求めることなく、新しいアクセストークンを取得するために使用されるトークン。" cta="用語集を見る" href="/ja/docs/glossary?term=Refresh+tokens">リフレッシュトークン</Tooltip>は、ユーザーに再認証を求めることなく、新しい<Tooltip tip="リフレッシュトークン: ユーザーに再度ログインを求めることなく、新しいアクセストークンを取得するために使用されるトークン。" cta="用語集を見る" href="/ja/docs/glossary?term=access+token">アクセストークン</Tooltip>や<Tooltip tip="アクセストークン: API へのアクセスに使用される、不透明な文字列または JWT の形式の認可クレデンシャル。" cta="用語集を見る" href="/ja/docs/glossary?term=ID+token">IDトークン</Tooltip>を要求するために使用されます。

通常は、前のアクセストークンの有効期限が切れる前に新しいアクセストークンを要求する必要があります (サービスの中断を避けるため) 。ただし、トークン交換には[レート制限ポリシー](/ja/docs/troubleshoot/customer-support/operational-policies/rate-limit-policy)が適用されるため、API を呼び出すたびに要求すべきではありません。

また、リフレッシュトークンを使用してユーザーの新しいIDトークンを要求することもできます。IDトークン内のクレームを更新する必要がある場合は、そうしてください。

<div id="call-the-api">
  ## API を呼び出す
</div>

認証時に受け取ったリフレッシュトークンを新しいアクセストークンに交換するには、Auth0 Authentication API の [Get token endpoint](https://auth0.com/docs/api/authentication#refresh-token) を呼び出します。

Authentication API で利用可能な認証方法の詳細については、[Authentication Methods](https://auth0.com/docs/api/authentication#authentication-methods) を参照してください。

<div id="use-basic-authentication">
  ### Basic認証を使用する
</div>

<AuthCodeGroup>
  ```bash cURL theme={null}
  curl --request POST \
    --url 'https://{yourDomain}/oauth/token' \
    --header 'authorization: Basic {yourApplicationCredentials}' \
    --header 'content-type: application/x-www-form-urlencoded' \
    --data grant_type=refresh_token \
    --data 'client_id={yourClientId}' \
    --data 'refresh_token={yourRefreshToken}'
  ```

  ```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.AddHeader("authorization", "Basic {yourApplicationCredentials}");
  request.AddParameter("application/x-www-form-urlencoded", "grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D", 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=%7ByourRefreshToken%7D")

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

  	req.Header.Add("content-type", "application/x-www-form-urlencoded")
  	req.Header.Add("authorization", "Basic {yourApplicationCredentials}")

  	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")
    .header("authorization", "Basic {yourApplicationCredentials}")
    .body("grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D")
    .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',
      authorization: 'Basic {yourApplicationCredentials}'
    },
    data: new URLSearchParams({
      grant_type: 'refresh_token',
      client_id: '{yourClientId}',
      refresh_token: '{yourRefreshToken}'
    })
  };

  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=%7ByourRefreshToken%7D",
    CURLOPT_HTTPHEADER => [
      "authorization: Basic {yourApplicationCredentials}",
      "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=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D"

  headers = {
      'content-type': "application/x-www-form-urlencoded",
      'authorization': "Basic {yourApplicationCredentials}"
      }

  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["authorization"] = 'Basic {yourApplicationCredentials}'
  request.body = "grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D"

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

<div id="use-post-authentication">
  ### Post authentication の使用
</div>

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

  ```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=refresh_token&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&refresh_token=%7ByourRefreshToken%7D", 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}&client_secret=%7ByourClientSecret%7D&refresh_token=%7ByourRefreshToken%7D")

  	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=refresh_token&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&refresh_token=%7ByourRefreshToken%7D")
    .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: 'refresh_token',
      client_id: '{yourClientId}',
      client_secret: '{yourClientSecret}',
      refresh_token: '{yourRefreshToken}'
    })
  };

  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}&client_secret=%7ByourClientSecret%7D&refresh_token=%7ByourRefreshToken%7D",
    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=refresh_token&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&refresh_token=%7ByourRefreshToken%7D"

  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=refresh_token&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&refresh_token=%7ByourRefreshToken%7D"

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

<div id="parameter-definition">
  ### パラメーター定義
</div>

| Parameter       | Description                                                       |
| --------------- | ----------------------------------------------------------------- |
| `grant_type`    | 実行するグラントの種類。                                                      |
| `client_id`     | アプリケーションのクライアントID。                                                |
| `client_secret` | (省略可能) アプリケーションのクライアントシークレット。POST トークン認証方式を使用する機密アプリケーションでのみ必要です。 |
| `refresh_token` | 交換対象のリフレッシュトークン。                                                  |

レスポンスには、新しいアクセストークン、トークンタイプ、有効期間 (秒単位) 、および付与されたスコープが含まれます。初期トークンのスコープに `openid` が含まれていた場合は、新しいIDトークンもレスポンスに含まれます。

```json lines theme={null}
{
      "access_token": "eyJ...MoQ",
      "expires_in": 86400,
      "scope": "openid offline_access",
      "id_token": "eyJ...0NE",
      "token_type": "Bearer"
    }
```

<div id="bypass-mfa">
  ## MFA をバイパスする
</div>

[多要素認証 (MFA) ](/ja/docs/secure/multi-factor-authentication) が有効で、リフレッシュトークンの交換フローが失敗した場合は、以下の Action コードを使用して <Tooltip tip="多要素認証（MFA）: SMS で送信されるコードなど、ユーザー名とパスワードに加えて認証要素を使用するユーザー認証プロセス。" cta="用語集を表示" href="/ja/docs/glossary?term=MFA">MFA</Tooltip> ロジックをバイパスできます。

```js lines theme={null}
exports.onExecutePostLogin = async (event, api) => {
  // このActionを使用すると、リフレッシュトークン交換フローのMFAロジックをバイパスできます。

  if (event.transaction.protocol === "oauth2-refresh-token") {
    return;
  }

  //  MFAロジックを追加する
  //  例: api.multifactor.enable("any");
};
```

現在のフローまたはプロトコルに応じて、別のロジックを実行する必要がある場合やスキップする必要がある場合は、コード例をカスタマイズできます。

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

<Warning>
  Resource Owner Password Grant、Embedded、またはリフレッシュトークンフローでのカスタマイズ可能な 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 Triggers: 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/get-refresh-tokens)
* [リフレッシュトークンを失効させる](/ja/docs/secure/tokens/refresh-tokens/revoke-refresh-tokens)
* [リフレッシュトークンの有効期限を設定する](/ja/docs/secure/tokens/refresh-tokens/configure-refresh-token-expiration)
* [Lock.Android: JSON Web Token を更新する](/ja/docs/libraries/lock-android/lock-android-refresh-jwt)
