> ## Documentation Index
> Fetch the complete documentation index at: https://auth0.com/llms.txt
> Use this file to discover all available pages before exploring further.

# リフレッシュトークンの取り消し

> Authentication API、Management API、またはAuth0 Dashboardを使用してリフレッシュ トークンが侵害された場合に、リフレッシュトークンを取り消す方法を学びます。

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

リフレッシュトークンが侵害された場合に備えて、リフレッシュトークンを取り消すことができます。Auth0は、トークンが悪意のある攻撃者にさらされている可能性があるかのように、トークンの失効を処理します。

また、クライアントが新しいアクセス トークンを取得するためにリフレッシュトークンを交換するたびに、新しいリフレッシュトークンも返されるように、[リフレッシュトークンのローテーション](/docs/ja-jp/secure/tokens/refresh-tokens/refresh-token-rotation)を使用することもできます。このため、侵入を受けると永久にリソースへのアクセスを許してしまうような、寿命の長いリフレッシュトークンはなくなりました。リフレッシュトークンは交換され続け、失効し続けるため、脅威の軽減に繋がっています。

次の方法でリフレッシュトークンを無効化することができます。

* ダッシュボード内
* 認証`/oauth/revoke`エンドポイントにPOST要求を行う
* <Tooltip data-tooltip-id="react-containers-DefinitionTooltip-0" href="/docs/ja-jp/glossary?term=management-api" tip="Management API: 顧客が管理タスクを実行できるようにするための製品。" cta="用語集の表示">Management API</Tooltip>`/api/v2/device-credentials`エンドポイントにPOST要求を行う

## トークンと付与を更新する

付与により、アプリケーションはユーザー資格情報を公開することなく、別のエンティティ上のリソースにアクセスできるようになります。トークンは付与の文脈で発行され、付与が無効化されると、その付与の文脈で発行されたすべてのトークンも無効化されます。一方、トークンが無効化された場合、必ずしも付与が無効化されるわけではありません。

DashboardまたはManagement APIを使用して、デバイスがAuth0のユーザーからリンク解除されたときに、Dashboardのテナント設定で取り消し動作を選択できます。

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  この機能は、既存のテナントに対しては、これまでの動作を維持するためにデフォルトで有効になっています。新しいテナント（2021年1月13日現在）に対しては、リフレッシュトークンを取り消しても付与が取り消されないように、この機能がデフォルトで無効化されます。付与の取り消しが必要な場合は、付与取り消しエンドポイントを使用して個別に要求を送らなければなりません。
</Callout>

1. Go to [［Dashboard］ > ［Tenant Settings（テナント設定）］ > ［Advanced（詳細）］](https://manage.auth0.com/#/tenant/advanced)に移動し、**［Settings（設定）］** セクションにスクロールします。
2. 失効をどのように動作させたいかに応じて、**リフレッシュトークン失効削除許可トグル** を有効または無効にします。

   1. リフレッシュトークンを無効化する際に基礎となる許可を削除するには、トグルを有効にします。取り消し要求ごとに、特定のトークンだけでなく、同じ認可付与に基づくその他すべてのトークンを無効にします。つまり、同じユーザー、アプリケーション、オーディエンスに発行されたリフレッシュトークンがすべて取り消されます。
   2. リフレッシュトークンを無効化する際に基礎となる許可を保持するには、トグルを無効にします。デバイスのリンクが解除されると、関連付けられたリフレッシュトークンのみが取り消され、許可はそのまま残ります。

## Dashboardの使用

Dashboardを使用して、トークンを発行したアプリケーションへのユーザーの承認済みアクセスを取り消すことができます。これにより、リフレッシュトークンが無効になります。これは、トークン自体を取り消すのと機能的に同じです。

1. [［Dashboard］>［User Management（ユーザー管理）］>［Users（ユーザー）］](https://manage.auth0.com/#/users)に移動し、ユーザー名をクリックして表示します。
2. **［Authorized Application（認可アプリケーション）］** タブを選択します。このページには、ユーザーがアクセスを許可したすべてのアプリケーションが一覧表示されます。
3. 承認済みアプリケーションへのユーザーのアクセスを取り消して、リフレッシュトークンを無効にするには、**［Revoke（取り消し）］** をクリックします。

## Authentication APIを使用する

リフレッシュトークンを取り消すには、`https://{yourDomain}/oauth/revoke`に`POST`要求を送信します。

`/oauth/revoke`エンドポイントは、特定のトークンだけでなく、許可全体を取り消します。リフレッシュトークンを取り消すには、`/api/v2/device-credentials`エンドポイントを使用します。APIは最初にアプリケーションの資格情報を検証し、次にトークンが取り消し要求を行ったアプリケーションに発行されたかどうかを確認します。この検証が失敗すると、要求は拒否され、アプリケーションにエラーが通知されます。次に、APIはトークンを無効にします。無効化は直ちに行われ、取り消し後はトークンを再び使用することはできません。取り消し要求ごとに、同じ承認許可に対して発行されたすべてのトークンが無効になります。

<AuthCodeGroup>
  ```bash cURL theme={null}
  curl --request POST \
    --url 'https://{yourDomain}/oauth/revoke' \
    --header 'content-type: application/json' \
    --data '{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "token": "{yourRefreshToken}" }'
  ```

  ```csharp C# theme={null}
  var client = new RestClient("https://{yourDomain}/oauth/revoke");
  var request = new RestRequest(Method.POST);
  request.AddHeader("content-type", "application/json");
  request.AddParameter("application/json", "{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "token": "{yourRefreshToken}" }", 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/revoke"

  	payload := strings.NewReader("{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "token": "{yourRefreshToken}" }")

  	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/revoke")
    .header("content-type", "application/json")
    .body("{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "token": "{yourRefreshToken}" }")
    .asString();
  ```

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

  var options = {
    method: 'POST',
    url: 'https://{yourDomain}/oauth/revoke',
    headers: {'content-type': 'application/json'},
    data: {
      client_id: '{yourClientId}',
      client_secret: '{yourClientSecret}',
      token: '{yourRefreshToken}'
    }
  };

  axios.request(options).then(function (response) {
    console.log(response.data);
  }).catch(function (error) {
    console.error(error);
  });
  ```

  ```objc Obj-C theme={null}
  #import <Foundation/Foundation.h>

  NSDictionary *headers = @{ @"content-type": @"application/json" };
  NSDictionary *parameters = @{ @"client_id": @"{yourClientId}",
                                @"client_secret": @"{yourClientSecret}",
                                @"token": @"{yourRefreshToken}" };

  NSData *postData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];

  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://{yourDomain}/oauth/revoke"]
                                                         cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                     timeoutInterval:10.0];
  [request setHTTPMethod:@"POST"];
  [request setAllHTTPHeaderFields:headers];
  [request setHTTPBody:postData];

  NSURLSession *session = [NSURLSession sharedSession];
  NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
                                              completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                  if (error) {
                                                      NSLog(@"%@", error);
                                                  } else {
                                                      NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
                                                      NSLog(@"%@", httpResponse);
                                                  }
                                              }];
  [dataTask resume];
  ```

  ```php PHP theme={null}
  $curl = curl_init();

  curl_setopt_array($curl, [
    CURLOPT_URL => "https://{yourDomain}/oauth/revoke",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_POSTFIELDS => "{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "token": "{yourRefreshToken}" }",
    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 = "{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "token": "{yourRefreshToken}" }"

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

  conn.request("POST", "/{yourDomain}/oauth/revoke", 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/revoke")

  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 = "{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "token": "{yourRefreshToken}" }"

  response = http.request(request)
  puts response.read_body
  ```

  ```swift Swift theme={null}
  import Foundation

  let headers = ["content-type": "application/json"]
  let parameters = [
    "client_id": "{yourClientId}",
    "client_secret": "{yourClientSecret}",
    "token": "{yourRefreshToken}"
  ] as [String : Any]

  let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

  let request = NSMutableURLRequest(url: NSURL(string: "https://{yourDomain}/oauth/revoke")! as URL,
                                          cachePolicy: .useProtocolCachePolicy,
                                      timeoutInterval: 10.0)
  request.httpMethod = "POST"
  request.allHTTPHeaderFields = headers
  request.httpBody = postData as Data

  let session = URLSession.shared
  let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
    if (error != nil) {
      print(error)
    } else {
      let httpResponse = response as? HTTPURLResponse
      print(httpResponse)
    }
  })

  dataTask.resume()
  ```
</AuthCodeGroup>

ここでは、

| 属性                  | 説明                                                                                                                                     |
| ------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| `client_id`<br />必須 | アプリケーションのクライアントID。アプリケーションは、リフレッシュトークンが発行されたものと一致する必要があります。                                                                            |
| `client_secret`     | [アプリケーションのクライアントシークレット。]("/docs/ja-jp/applications/concepts/app-types-confidential-public#confidential-applications">機密アプリケーション)に必要です。 |
| `token`<br />必須     | 取り消したいリフレッシュトークン。                                                                                                                      |

アプリケーションは、リフレッシュトークンが発行されたものと一致する必要があります。

### クライアントシークレットなしでトークンを取り消す

クライアントシークレットを安全に保管できないアプリケーション（ネイティブアプリなど）の場合、`/oauth/revoke`エンドポイントはクライアントシークレットなしでのアクセスをサポートします。ただし、アプリケーション自体の`tokenEndpointAuthMethod`プロパティが`none`に設定されている必要があります。`tokenEndpointAuthMethod`値は、[［Dashboard］ > ［Applications（アプリケーション）］ > ［Applications（アプリケーション）］](https://manage.auth0.com/#/applications)から、またはManagement APIを使用して変更できます。

要求が有効な場合、リフレッシュトークンは取り消され、応答は`HTTP 200`で、応答本文は空です。それ以外の場合、応答本文にはエラーコードと説明が含まれます。

```json lines theme={null}
{
      "error": "invalid_request|invalid_client",
      "error_description": "Description of the error"
    }
```

考えられる応答は次のとおりです。

| HTTPステータス | 説明                                                                                                                |
| --------- | ----------------------------------------------------------------------------------------------------------------- |
| 200       | リフレッシュトークンが取り消された、存在しない、または取り消し要求を行うアプリケーションに対して発行されていません。応答本文は空欄のままです。                                           |
| 400       | 必要なパラメーターが要求で送信されませんでした（`"error":"invalid_request"`）。                                                             |
| 401       | 要求は承認されていません（`"error": "invalid_client"`）。アプリケーションの資格情報（`client_id`と`client_secret`）が要求に存在し、有効な値が指定されていることを確認します。 |

## Management APIの使用

Auth0 Management APIを使用してリフレッシュトークンを取り消すには、取り消すリフレッシュトークンの`id`が必要です。既存のリフレッシュトークンのリストを取得するには、`/api/v2/device-credentials`[エンドポイント](/docs/ja-jp/api/management/v2#!/Device_Credentials/get_device_credentials)を呼び出し、`type=refresh_token`と`user_id`を指定して、`read:device_credentials`スコープを含むアクセス トークンを使用します。結果を絞り込むには、トークンに関連付けられた`client_id`（わかっている場合）を指定することもできます。

export const codeExample11 = `GET https://{yourDomain}/api/v2/device-credentials?
      type=refresh_token
      &client_id=
      &user_id=
    
    {
      "Authorization":   "Bearer {your_access_token}"
    }`;

<AuthCodeBlock children={codeExample11} language="json" />

応答本文：

```json lines theme={null}
[
      {
    "id": "dcr_dFJiaAxbEroQ5xxx",
    "device_name": "my-device" // the value of 'device' provided in the /authorize call when creating the token
      }
    ]
```

リフレッシュトークンを取り消すには、`delete:device_credentials`スコープを含むアクセス トークンと上記で取得した ID の値を使用して、`/api/v2/device-credentials`エンドポイントを呼び出します。

export const codeExample12 = `DELETE https://{yourDomain}/api/v2/device-credentials/{id}
    
    {
      "Authorization":   "Bearer {your_access_token}"
    }`;

<AuthCodeBlock children={codeExample12} language="javascript" />

応答は`HTTP 204: The credential no longer exists`（認証情報はもう存在しません）になります。

## 考慮事項と制限

[デバイス認可フロー](/docs/ja-jp/get-started/authentication-and-authorization-flow/device-authorization-flow)では、デバイスに再認証を強制する唯一の方法は、デバイスに割り当てられたリフレッシュトークンを取り消すことです。詳細については、[ユーザーからデバイスのリンクを解除する](/docs/ja-jp/manage-users/user-accounts/unlink-devices-from-users)を参照してください。デバイスは、現在有効なアクセストークンの期限が切れて、アプリケーションが失効したリフレッシュトークンを使おうとするまでは、再認証が強制されないことに注意してください。

[リフレッシュトークンのローテーション](/docs/ja-jp/secure/tokens/refresh-tokens/refresh-token-rotation)使用中に以前無効になったトークンが使用されている場合は、その無効になったトークンが発行された以降に発行されたリフレッシュトークンの全セットが付与と同様に直ちに失効され、ユーザーの再認証が必要になります。

* リフレッシュトークンを取り消すには、Authentication APIの`/oauth/revoke`[エンドポイント](/docs/ja-jp/api/authentication#revoke-refresh-token)を使用します。このエンドポイントは、基礎となる許可を削除しません。この動作を変更して、Dashboardで基礎となる許可も削除できます。[［Dashboard］ > ［Tenant Settings（テナント設定）］ > ［Advanced（詳細）］](https://manage.auth0.com/#/tenant/advanced)。**Settings（設定）** までスクロールし、**リフレッシュトークンの取り消しによる許可の削除** のトグルを有効にします。
* ローテーション用に構成されたリフレッシュトークンを取り消すには、Management API`/api/v2/device-credentials`[エンドポイント](/docs/ja-jp/api/management/v2#!/Device_Credentials/get_device_credentials)を使用します。

## もっと詳しく

* [リフレッシュトークンの取得](/docs/ja-jp/secure/tokens/refresh-tokens/get-refresh-tokens)
* [リフレッシュトークンの使用](/docs/ja-jp/secure/tokens/refresh-tokens/use-refresh-tokens)
* [リフレッシュトークンのローテーション](/docs/ja-jp/secure/tokens/refresh-tokens/refresh-token-rotation)
* [リフレッシュトークンの有効期限を構成する](/docs/ja-jp/secure/tokens/refresh-tokens/configure-refresh-token-expiration)
