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

> 高信頼アプリケーションから、Resource Owner Password Flow を使用して独自のAPIを呼び出す方法を学びます。

# Resource Owner Password Flow を使用して独自のAPIを呼び出す

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

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  このチュートリアルでは、Resource Owner Password Flow を使用して独自の API を呼び出す方法を説明します。このフローの仕組みや、これを使用すべき理由については、[Resource Owner Password Flow](/docs/ja-jp/get-started/authentication-and-authorization-flow/resource-owner-password-flow) を参照してください。
</Callout>

<Warning>
  Resource Owner Password (ROP) フローではアプリケーションがユーザーのパスワードを扱うため、サードパーティのクライアントでは使用しないでください。
</Warning>

Auth0 では、[Authentication API](https://auth0.com/docs/api/authentication) を使って、アプリに <Tooltip tip="リソース所有者: 保護されたリソースへのアクセスを許可できるエンティティ（ユーザーやアプリケーションなど）。" cta="用語集を見る" href="/docs/ja-jp/glossary?term=Resource+Owner">リソース所有者</Tooltip> Password Flow (Resource Owner Password Grant または ROPG とも呼ばれます) を簡単に実装できます。以降では、API を直接呼び出す方法を説明します。

<div id="prerequisites">
  ## 前提条件
</div>

**このチュートリアルを始める前に:**

* [Auth0 にアプリケーションを登録する](/docs/ja-jp/get-started/auth0-overview/create-applications/regular-web-apps).

  * **アプリケーションの種類** として **Regular Web Apps** を選択します。
  * **Allowed Callback URL** に `{https://yourApp/callback}` を追加します。このフィールドは空欄にできません。空欄のままだとエラーメッセージが返されます。
  * アプリケーションの **グラントタイプ** に **パスワード** が含まれていることを確認します。設定方法については、[グラントタイプを更新する](/docs/ja-jp/get-started/applications/update-grant-types) を参照してください。
  * アプリケーションでリフレッシュトークンを使用できるようにするには、アプリケーションの **グラントタイプ** に **リフレッシュトークン** が含まれていることを確認します。設定方法については、[グラントタイプを更新する](/docs/ja-jp/get-started/applications/update-grant-types) を参照してください。リフレッシュトークンの詳細については、[リフレッシュトークン](/docs/ja-jp/secure/tokens/refresh-tokens) を参照してください。
* [Auth0 に API を登録する](/docs/ja-jp/get-started/auth0-overview/set-up-apis)

  * 以前のトークンの有効期限が切れたときに API が新しいトークンを取得できるよう、API でリフレッシュトークンを受け取れるようにする場合は、**オフラインアクセスの許可** を有効にします。
* 接続を設定する

  * 接続がユーザー名とパスワードでユーザーを認証できることを確認します (たとえば、[データベース接続](/docs/ja-jp/get-started/applications/set-up-database-connections) や、AD/LDAP、ADFS、または Azure Active Directory の [エンタープライズ接続](/docs/ja-jp/authenticate/identity-providers/enterprise-identity-providers)) 。
* 特定の接続にのみ影響するように、[ルール](/docs/ja-jp/customize/rules) を更新または無効化します。Password Owner Resource Grant のテスト中に `access_denied` エラーが発生した場合は、アクセス制御ルールが原因の可能性があります。

<div id="steps">
  ## 手順
</div>

1. [テナントを設定する](#configure-tenant):テナントのデフォルト接続を設定します。
2. [トークンをリクエストする](#request-tokens):
   認可コードをトークンに交換します。
3. [API を呼び出す](#call-api):
   取得したアクセストークンを使用して API を呼び出します。
4. [リフレッシュトークン](#refresh-tokens):
   既存のトークンの有効期限が切れたら、リフレッシュトークンを使用して新しいトークンをリクエストします。

任意: [サンプルのユースケースを確認する](#sample-use-cases)

任意: [レルムのサポートを設定する](#configure-realm-support)

任意: [MFA を設定する](#configure-mfa)

任意: [攻撃対策を設定する](#configure-anomaly-detection)

<div id="configure-tenant">
  ### テナントを設定する
</div>

Resource Owner Password Flow では、ユーザー名とパスワードでユーザーを認証できる接続を使用するため、テナントのデフォルト接続を設定する必要があります。

1. [Auth0 Dashboard > Tenant Settings](https://manage.auth0.com/#/tenant) に移動し、下にスクロールして **Default Directory** 設定を探します。
2. 使用する接続の名前を入力します。その接続が、ユーザー名とパスワードでユーザーを認証できることを確認してください。

<div id="request-tokens">
  ### トークンをリクエストする
</div>

API を呼び出すには、まず通常はインタラクティブなフォームを通じてユーザーの資格情報を取得する必要があります。アプリケーションが資格情報を取得したら、それをトークンに交換する必要があります。そのためには、[トークン URL](https://auth0.com/docs/api/authentication#resource-owner-password) に `POST` する必要があります。

<div id="example-post-to-token-url">
  #### トークン URL に POST する例
</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=password \
    --data 'username={username}' \
    --data 'password={password}' \
    --data 'audience={yourApiIdentifier}' \
    --data scope=read:sample \
    --data 'client_id={yourClientId}' \
    --data 'client_secret={yourClientSecret}'
  ```

  ```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=password&username=%7Busername%7D&password=%7Bpassword%7D&audience=%7ByourApiIdentifier%7D&scope=read%3Asample&client_id={yourClientId}&client_secret=%7ByourClientSecret%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=password&username=%7Busername%7D&password=%7Bpassword%7D&audience=%7ByourApiIdentifier%7D&scope=read%3Asample&client_id={yourClientId}&client_secret=%7ByourClientSecret%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 response = Unirest.post("https://{yourDomain}/oauth/token")
    .header("content-type", "application/x-www-form-urlencoded")
    .body("grant_type=password&username=%7Busername%7D&password=%7Bpassword%7D&audience=%7ByourApiIdentifier%7D&scope=read%3Asample&client_id={yourClientId}&client_secret=%7ByourClientSecret%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: 'password',
      username: '{username}',
      password: '{password}',
      audience: '{yourApiIdentifier}',
      scope: 'read:sample',
      client_id: '{yourClientId}',
      client_secret: '{yourClientSecret}'
    })
  };

  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=password&username=%7Busername%7D&password=%7Bpassword%7D&audience=%7ByourApiIdentifier%7D&scope=read%3Asample&client_id={yourClientId}&client_secret=%7ByourClientSecret%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=password&username=%7Busername%7D&password=%7Bpassword%7D&audience=%7ByourApiIdentifier%7D&scope=read%3Asample&client_id={yourClientId}&client_secret=%7ByourClientSecret%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_PEER

  request = Net::HTTP::Post.new(url)
  request["content-type"] = 'application/x-www-form-urlencoded'
  request.body = "grant_type=password&username=%7Busername%7D&password=%7Bpassword%7D&audience=%7ByourApiIdentifier%7D&scope=read%3Asample&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D"

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

##### パラメータ

| パラメータ名                  | 説明                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `grant_type`            | `password` に設定します。                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `username`              | ユーザーが入力したユーザー名。                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `password`              | ユーザーが入力したパスワード。                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `client_id`             | アプリケーションの Client ID。値は [アプリケーション設定](https://manage.auth0.com/#/Applications/\{yourClientId}/settings) で確認できます。                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `client_assertion`      | アプリケーションの資格情報を使用して署名したアサーションを含む JWT。Private Key JWT がアプリケーションの認証方法である場合に必要です。                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `client_assertion_type` | 値は `urn:ietf:params:oauth:client-assertion-type:jwt-bearer` です。Private Key JWT がアプリケーションの認証方法である場合に必要です。                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| `client_secret`         | アプリケーションの Client Secret。Client Secret がアプリケーションの認証方法である場合に必要です。[アプリケーション設定](https://manage.auth0.com/#/applications/\{yourClientId}/settings) が `Post` または `Basic` の場合に使用します。アプリケーションの信頼性が高くない場合 (たとえば SPA) には、このパラメータを設定しないでください。                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `audience`              | トークンの audience、つまり API を指定します。これは [API の設定タブ](https://manage.auth0.com/#/apis) の **Identifier** フィールドで確認できます。                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `scope`                 | 認可をリクエストする [scopes](/docs/ja-jp/get-started/apis/scopes) を指定します。これにより、返されるクレーム (またはユーザー属性) が決まります。各値はスペースで区切る必要があります。`profile` や `email` などのユーザーに関する [標準 OpenID Connect (OIDC) scopes](https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims)、[namespaced format](/docs/ja-jp/secure/tokens/json-web-tokens/create-custom-claims) に準拠した [custom claims](/docs/ja-jp/secure/tokens/json-web-tokens/json-web-token-claims#custom-claims)、または対象 API がサポートする任意の scopes (例: `read:contacts`) をリクエストできます。[リフレッシュトークン](/docs/ja-jp/glossary?term=Refresh+Token) を取得するには `offline_access` を含めてください ([アプリケーション設定](https://manage.auth0.com/#/applications) で **オフラインアクセスの許可** フィールドが有効になっていることを確認してください) 。 |

<div id="response">
  #### レスポンス
</div>

問題なく処理されると、`access_token`、`refresh_token`、`id_token`、`token_type`、`expires_in` の各値を含むペイロードを持つ `HTTP 200` レスポンスが返されます：

```json lines theme={null}
{
  "access_token": "eyJz93a...k4laUWw",
  "refresh_token": "GEbRxBN...edjnXbL",
  "id_token": "eyJ0XAi...4faeEoQ",
  "token_type": "Bearer",
  "expires_in": 36000
}
```

<Warning>
  保存する前にトークンを検証してください。方法については、[ID トークンを検証する](/docs/ja-jp/secure/tokens/id-tokens/validate-id-tokens)および[アクセストークンを検証する](/docs/ja-jp/secure/tokens/access-tokens/validate-access-tokens)を参照してください。
</Warning>

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

<Card title="Resource Owner Password フローと標準スコープ">
  パスワードを提供すると完全なアクセス権が与えられるため、パスワードベースのあらゆるやり取りで、すべてのスコープへのアクセスが付与されます。たとえば、リクエストに[API スコープ](/docs/ja-jp/get-started/apis/scopes/api-scopes)を含めない場合、すべての API スコープがアクセストークンに含まれます。同様に、リクエストに `openid` スコープのみを含めた場合は、`openid` の標準[OpenID Connect スコープ](/docs/ja-jp/get-started/apis/scopes/openid-connect-scopes)がすべて返されます。これらのケースでは、レスポンスに `scope` パラメーターが含まれ、発行されたスコープが一覧表示されます。
</Card>

<Card title="ID トークンなしでユーザー情報を取得する">
  ユーザー情報が必要な場合は、リクエストに `openid` スコープを含めてください。API が[署名アルゴリズム](/docs/ja-jp/get-started/applications/signing-algorithms)として `RS256` を使用している場合、アクセストークンには有効な audience として `/userinfo` が含まれます。つまり、そのアクセストークンを使用して [/userinfo endpoint](https://auth0.com/docs/api/authentication#get-user-info) を呼び出し、ユーザーのクレームを取得できます。
</Card>

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

API を呼び出すには、アプリケーションで取得した <Tooltip tip="アクセストークン: API へのアクセスに使用される認可資格情報で、不透明な文字列または JWT の形式です。" cta="用語集を見る" href="/docs/ja-jp/glossary?term=Access+Token">アクセストークン</Tooltip> を、HTTP リクエストの Authorization ヘッダーで Bearer トークンとして渡す必要があります。

<AuthCodeGroup>
  ```bash cURL lines theme={null}
  curl --request GET \
    --url https://myapi.com/api \
    --header 'authorization: Bearer {accessToken}' \
    --header 'content-type: application/json'
  ```

  ```csharp C# lines theme={null}
  var client = new RestClient("https://myapi.com/api");
  var request = new RestRequest(Method.GET);
  request.AddHeader("content-type", "application/json");
  request.AddHeader("authorization", "Bearer {accessToken}");
  IRestResponse response = client.Execute(request);
  ```

  ```go Go lines expandable theme={null}
  package main

  import (
  	"fmt"
  	"net/http"
  	"io/ioutil"
  )

  func main() {

  	url := "https://myapi.com/api"

  	req, _ := http.NewRequest("GET", url, nil)

  	req.Header.Add("content-type", "application/json")
  	req.Header.Add("authorization", "Bearer {accessToken}")

  	res, _ := http.DefaultClient.Do(req)

  	defer res.Body.Close()
  	body, _ := ioutil.ReadAll(res.Body)

  	fmt.Println(res)
  	fmt.Println(string(body))

  }
  ```

  ```java Java lines theme={null}
  HttpResponse response = Unirest.get("https://myapi.com/api")
    .header("content-type", "application/json")
    .header("authorization", "Bearer {accessToken}")
    .asString();
  ```

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

  var options = {
    method: 'GET',
    url: 'https://myapi.com/api',
    headers: {'content-type': 'application/json', authorization: 'Bearer {accessToken}'}
  };

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

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

  curl_setopt_array($curl, [
    CURLOPT_URL => "https://myapi.com/api",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "GET",
    CURLOPT_HTTPHEADER => [
      "authorization: Bearer {accessToken}",
      "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 lines theme={null}
  import http.client

  conn = http.client.HTTPSConnection("myapi.com")

  headers = {
      'content-type': "application/json",
      'authorization': "Bearer {accessToken}"
      }

  conn.request("GET", "/api", headers=headers)

  res = conn.getresponse()
  data = res.read()

  print(data.decode("utf-8"))
  ```

  ```ruby Ruby lines theme={null}
  require 'uri'
  require 'net/http'
  require 'openssl'

  url = URI("https://myapi.com/api")

  http = Net::HTTP.new(url.host, url.port)
  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL::VERIFY_PEER

  request = Net::HTTP::Get.new(url)
  request["content-type"] = 'application/json'
  request["authorization"] = 'Bearer {accessToken}'

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

<div id="refresh-tokens">
  ### リフレッシュトークン
</div>

このチュートリアルをここまで進め、次の手順を完了していれば、すでに[リフレッシュトークン](/docs/ja-jp/secure/tokens/refresh-tokens)を受け取っているはずです。

* APIでオフラインアクセスの許可を有効にした
* [authorize endpoint](https://auth0.com/docs/api/authentication/reference#authorize-application)を通じてAuthentication Requestを開始する際に、`offline_access`スコープを含めた

新しいアクセストークンを取得するには、<Tooltip tip="リフレッシュトークン: ユーザーに再度ログインさせることなく、新しいアクセストークンを取得するために使用されるトークン。" cta="用語集を見る" href="/docs/ja-jp/glossary?term=Refresh+Token">リフレッシュトークン</Tooltip>を使用できます。通常、ユーザーが新しいアクセストークンを必要とするのは、前のトークンの有効期限が切れた後か、新しいリソースに初めてアクセスするときだけです。APIを呼び出すたびに新しいアクセストークンを取得するためにエンドポイントを毎回呼び出すのは望ましくありません。さらに、Auth0ではrate limitsが設けられており、同じIPから同じトークンを使用してそのエンドポイントに送信できるリクエスト数は制限されます。

トークンを更新するには、`grant_type=refresh_token`を使用して、Authentication APIの`/oauth/token`エンドポイントに`POST`リクエストを送信します。

<div id="example-post-to-token-url">
  #### トークン URL に POST する例
</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 '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}&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")

  	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 response = Unirest.post("https://{yourDomain}/oauth/token")
    .header("content-type", "application/x-www-form-urlencoded")
    .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'},
    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 => [
      "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" }

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

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

<div id="parameters">
  ##### パラメーター
</div>

| パラメーター名         | 説明                                                                                                                  |
| --------------- | ------------------------------------------------------------------------------------------------------------------- |
| `grant_type`    | `refresh_token` に設定します。                                                                                             |
| `client_id`     | アプリケーションの Client ID です。この値は [アプリケーション設定](https://manage.auth0.com/#/Applications/\{yourClientId}/settings) で確認できます。 |
| `refresh_token` | 使用するリフレッシュトークンです。                                                                                                   |
| `scope`         | (任意) 要求するスコープ権限をスペース区切りで指定します。送信しない場合は元のスコープが使用され、送信する場合はより限定されたスコープのセットを要求できます。なお、これは URL エンコードする必要があります。          |

<div id="response">
  #### レスポンス
</div>

正常に処理されると、新しい `access_token`、その有効期間 (秒単位の `expires_in`) 、付与された `scope` の値、`token_type` を含むペイロードとともに、`HTTP 200` レスポンスが返されます。

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

<Warning>
  保存する前に、トークンを検証してください。詳しくは、[ID トークンを検証する](/docs/ja-jp/secure/tokens/id-tokens/validate-id-tokens) と [アクセストークンを検証する](/docs/ja-jp/secure/tokens/access-tokens/validate-access-tokens) を参照してください。
</Warning>

<div id="sample-use-cases">
  ### 使用例
</div>

<div id="customize-tokens">
  #### トークンをカスタマイズする
</div>

Actions を使用すると、返されるアクセストークンのスコープを変更したり、アクセストークンや <Tooltip tip="ID Token: リソースへのアクセスではなく、クライアント自体を対象とする認証情報。" cta="用語集を見る" href="/docs/ja-jp/glossary?term=ID+Tokens">ID Token</Tooltip> にクレームを追加したりできます。 (Actions の詳細については、[Auth0 Actions](/docs/ja-jp/customize/actions) を参照してください。) そのためには、次の Action を追加します。これは、ユーザーが認証された後に実行されます。

```js lines theme={null}
exports.onExecutePostLogin = async (event, api) => {
  // アクセストークンと ID トークンにカスタムクレームを追加する
  api.accessToken.setCustomClaim('https://foo/bar', 'value');
  api.idToken.setCustomClaim('https://fiz/baz', 'some other value');

  // アクセストークンのスコープを変更する
  api.accessToken.addScope('foo');
  api.accessToken.addScope('bar');
};
```

スコープは、Action の実行後にトークン内で利用できるようになります。

<Warning>
  Auth0 は、[OpenID Connect (OIDC) specification](https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims) で定義されている構造化クレーム形式でプロファイル情報を返します。つまり、ID トークンまたはアクセストークンに追加するカスタムクレームは、競合の可能性を避けるため、[ガイドラインと制限事項に従う](/docs/ja-jp/secure/tokens/json-web-tokens/create-custom-claims) 必要があります。
</Warning>

<div id="configure-realm-support">
  ### レルムのサポートを設定する
</div>

Auth0 では、リソース所有者パスワードグラントと同様の機能を提供する拡張グラントを利用できます。これにより、別々のユーザーディレクトリ (それぞれ別の接続に対応) を維持したまま、フロー中にどれを使用するかを指定できます。

この方法を使用するには、次の操作が必要です。

* `grant_type` リクエストパラメーターを `http://auth0.com/oauth/grant-type/password-realm` に設定します。
* `realm` という追加のリクエストパラメーターを送信し、ユーザーが属するレルムの名前を設定します。たとえば、社内従業員向けに `employees` という名前のデータベース接続を設定しており、ユーザーがその接続に属している場合は、`realm` を `employees` に設定します。

<Card title="レルムとしての接続">
  アクティブ認証をサポートする接続であれば、[データベース接続](/docs/ja-jp/get-started/applications/set-up-database-connections)、[パスワードレス接続](/docs/ja-jp/authenticate/passwordless)、[AD/LDAP](/docs/ja-jp/authenticate/identity-providers/enterprise-identity-providers/active-directory-ldap)、[ADFS](/docs/ja-jp/authenticate/identity-providers/enterprise-identity-providers/adfs)、[Azure Active Directory](/docs/ja-jp/authenticate/identity-providers/enterprise-identity-providers/azure-active-directory/v2) のエンタープライズ接続を含め、レルムとして設定できます。
</Card>

<div id="configure-mfa">
  ### MFA を設定する
</div>

Resource Owner Password Flow を使用する必要があり、より強固な認証が必要な場合は、<Tooltip tip="多要素認証（MFA）: SMS で送信されるコードなど、ユーザー名とパスワードに加えて認証要素を使用するユーザー認証プロセス。" cta="用語集を見る" href="/docs/ja-jp/glossary?term=multi-factor+authentication">多要素認証</Tooltip> (MFA) を追加できます。詳しくは、[MFA を使用した Resource Owner Password Flow での認証](/docs/ja-jp/secure/multi-factor-authentication/authenticate-using-ropg-flow-with-mfa) をご覧ください。

<div id="configure-attack-protection">
  ### 攻撃対策を設定する
</div>

<Tooltip tip="総当たり攻撃対策: 単一のIPアドレスから単一のユーザーアカウントを標的として行われる総当たり攻撃から保護する攻撃対策の一形態です。" cta="用語集を表示" href="/docs/ja-jp/glossary?term=brute-force+protection">総当たり攻撃対策</Tooltip>を有効にした状態でResource Owner Password Flowを使用すると、一部の<Tooltip tip="総当たり攻撃対策: 単一のIPアドレスから単一のユーザーアカウントを標的として行われる総当たり攻撃から保護する攻撃対策の一形態です。" cta="用語集を表示" href="/docs/ja-jp/glossary?term=attack+protection">攻撃対策</Tooltip>機能が正常に動作しない場合があります。ただし、一般的な問題の一部は回避できます。詳しくは、[Resource Owner Password Flowと攻撃対策に関する一般的な問題を回避する](/docs/ja-jp/get-started/authentication-and-authorization-flow/resource-owner-password-flow/avoid-common-issues-with-resource-owner-password-flow-and-attack-protection)を参照してください。

<div id="learn-more">
  ## 詳細情報
</div>

* [OAuth 2.0 認可フレームワーク](/docs/ja-jp/authenticate/protocols/oauth)
* [OpenID Connect プロトコル](/docs/ja-jp/authenticate/protocols/openid-connect-protocol)
* [トークン](/docs/ja-jp/secure/tokens)
