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

> モバイル + API アーキテクチャ シナリオ向けの API とモバイルの構成

# API とモバイルの構成（モバイルアプリ + 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>;
};

このセクションでは、このシナリオ向けのAPIをどのように実装するかを見ていきます。

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  簡単にするため、この実装では認証と認可のみに焦点を当てます。サンプルで示すように、入力するタイムシートの項目はハードコードされており、APIでその項目が永続化されることはありません。代わりに、一部の情報をそのまま返すだけです。
</Callout>

<div id="define-the-api-endpoints">
  ## API エンドポイントを定義する
</div>

まず、API のエンドポイントを定義します。

<Card title="API エンドポイントとは何ですか？">
  **API エンドポイント**とは、オブジェクトを表す一意の URL です。このオブジェクトとやり取りするには、アプリケーションからその URL を指定する必要があります。たとえば、注文または顧客を返す API がある場合、`/orders` と `/customers` という 2 つのエンドポイントを設定できます。アプリケーションは、これらのエンドポイントに対して異なる HTTP メソッドを使ってやり取りします。たとえば、`POST /orders` で新しい注文を作成し、`GET /orders` で 1 つ以上の注文のデータセットを取得できます。
</Card>

この実装では、定義するエンドポイントは 2 つだけです。1 つは従業員のすべてのタイムシートの一覧を取得するためのもの、もう 1 つは従業員が新しいタイムシートエントリを作成するためのものです。

`/timesheets` エンドポイントへの `HTTP GET` リクエストにより、ユーザーは自分のタイムシートを取得できます。また、`/timesheets` エンドポイントへの `HTTP POST` リクエストにより、ユーザーは新しいタイムシートを追加できます。

実装については、[Node.js](/docs/ja-jp/get-started/architecture-scenarios/mobile-api/api-implementation-nodejs#1-define-the-api-endpoints) を参照してください。

<div id="secure-the-endpoints">
  ### エンドポイントを保護する
</div>

API がヘッダーに bearer <Tooltip tip="Access Token: API へのアクセスに使用される認可資格情報で、不透明な文字列または JWT の形式を取ります。" cta="用語集を見る" href="/docs/ja-jp/glossary?term=Access+Token">アクセストークン</Tooltip> を含むリクエストを受け取った場合、最初に行うべきことはそのトークンを検証することです。これには一連の手順があり、そのいずれかに失敗した場合は、呼び出し元のアプリに `Missing or invalid token` というエラーメッセージを返して、リクエストを拒否する必要があります。

API が実行すべき検証は次のとおりです。

* <Tooltip tip="JSON Web Token (JWT): 2 者間でクレームを安全に表現するために使用される標準的な ID トークン形式（多くの場合、アクセストークンの形式でもあります）。" cta="用語集を見る" href="/docs/ja-jp/glossary?term=JWT">JWT</Tooltip> が正しい形式であることを確認する
* 署名を確認する
* 標準クレームを検証する

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  [JWT.io](https://jwt.io/) では、JWT の解析、署名やクレームの検証など、作業の大部分を担えるライブラリの一覧を提供しています。
</Callout>

検証プロセスの一環として、クライアントの権限 (スコープ) も確認する必要がありますが、これについてはこのドキュメントの次の段落で別途説明します。

アクセストークンの検証について詳しくは、[Validate Access Tokens](/docs/ja-jp/secure/tokens/access-tokens/validate-access-tokens) を参照してください。

実装例については、[Node.js](/docs/ja-jp/get-started/architecture-scenarios/mobile-api/api-implementation-nodejs#2-secure-the-api-endpoints) を参照してください。

<div id="check-the-clients-permissions">
  ### クライアントの権限を確認する
</div>

ここまでで、JWT が有効であることを検証しました。最後の手順は、保護されたリソースへのアクセスに必要な権限をクライアントが持っていることを確認することです。

そのために、API はデコードされた JWT の [スコープ](/docs/ja-jp/get-started/apis/scopes) を確認する必要があります。この クレーム は ペイロード の一部で、空白区切りの文字列のリストです。

実装については、[Node.js](/docs/ja-jp/get-started/architecture-scenarios/mobile-api/api-implementation-nodejs#3-check-the-client-permissions) を参照してください。

<div id="determine-user-identity">
  ### ユーザーの識別
</div>

どちらのエンドポイント (タイムシート一覧の取得と新しいタイムシートの追加) でも、ユーザーを識別する必要があります。

タイムシート一覧を取得する際は、リクエストを行っているユーザーに属するタイムシートのみを返すために必要です。また、新しいタイムシートを追加する際は、そのタイムシートをリクエスト元のユーザーに関連付けるために必要です。

標準的な JWT クレームの 1 つに `sub` クレームがあり、これはクレームの対象となる主体を識別します。Implicit Grant フローでは、このクレームにユーザーの識別情報、つまり Auth0 ユーザーの一意の識別子が含まれます。これを使うことで、外部システム内の任意の情報を特定のユーザーに関連付けることができます。

また、カスタムクレームを使用して、ユーザーの別の属性 (メールアドレスなど) をアクセストークンに追加し、それを使ってユーザーを一意に識別することもできます。

実装については、[Node.js](/docs/ja-jp/get-started/architecture-scenarios/mobile-api/api-implementation-nodejs#4-determine-the-user-identity) を参照してください。

<div id="implement-the-mobile-app">
  ## モバイルアプリを実装する
</div>

このセクションでは、このシナリオに対応するモバイルアプリケーションの実装方法を見ていきます。

[Android での実装を見る](/docs/ja-jp/get-started/architecture-scenarios/mobile-api/mobile-implementation-android#1-set-up-the-application)

<div id="authorize-the-user">
  ### ユーザーを認可する
</div>

ユーザーを認可するには、[Authorization Code Flow with Proof Key for Code Exchange (PKCE)](/docs/ja-jp/get-started/authentication-and-authorization-flow/authorization-code-flow-with-pkce/call-your-api-using-the-authorization-code-flow-with-pkce) を実装します。モバイルアプリケーションはまず、`code_challenge` とその生成に使用したメソッドを指定して、ユーザーを [authorization URL](https://auth0.com/docs/api/authentication#authorization-code-grant-pkce-) にリダイレクトする必要があります。

export const codeExample1 = `https://{yourDomain}/authorize?
    audience=API_AUDIENCE&
    scope=SCOPE&
    response_type=code&
    client_id={yourClientId}&
    code_challenge=CODE_CHALLENGE&
    code_challenge_method=S256&
    redirect_uri=https://YOUR_APP/callback`;

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

認可 URL への `GET` リクエストには、次の値を含める必要があります。

| Parameter                   | Description                                                                                                                                                                                                                                                                                                                                                                                           |
| --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **client\_id**              | Auth0 Client Id の値です。[Auth0 Dashboard](https://manage.auth0.com/#/applications) のアプリケーションの Settings から取得できます。                                                                                                                                                                                                                                                                                         |
| **audience**                | API Identifier の値です。[Auth0 Dashboard](https://manage.auth0.com/#/apis) の API の Settings から取得できます。                                                                                                                                                                                                                                                                                                     |
| **scope**                   | IDトークン と アクセストークン で返される クレーム を決定する [スコープ](/docs/ja-jp/get-started/apis/scopes) です。たとえば、scope に `openid` を指定すると、レスポンスに IDトークン が含まれます。このモバイルアプリの例では、次の スコープ を使用します: `create:timesheets read:timesheets openid profile email offline_access`。これらの スコープ により、モバイルアプリは API を呼び出し、[Refresh Token](/docs/ja-jp/glossary?term=Refresh+Token) を取得し、IDトークン 内でユーザーの `name`、`picture`、`email` の クレーム を受け取ることができます。 |
| **response\_type**          | 使用する認証フローを示します。PKCE を使用するモバイルアプリケーションでは、`code` に設定する必要があります。                                                                                                                                                                                                                                                                                                                                          |
| **code\_challenge**         | code verifier から生成した code challenge です。code challenge の生成方法については、[こちら](/docs/ja-jp/get-started/authentication-and-authorization-flow/authorization-code-flow-with-pkce/call-your-api-using-the-authorization-code-flow-with-pkce#authorize-the-user%23create-a-code-verifier)を参照してください。                                                                                                               |
| **code\_challenge\_method** | challenge の生成に使用するメソッドです。Auth0 がサポートしているのは `S256` のみです。                                                                                                                                                                                                                                                                                                                                               |
| **redirect\_uri**           | ユーザーが認可を許可した後に、Auth0 がブラウザーをリダイレクトする先の URL です。認可コードは URL パラメーター `code` から取得できます。この URL は、[Application's Settings](https://manage.auth0.com/#/applications) で有効な callback URL として指定する必要があります。                                                                                                                                                                                                          |

[Android での実装を見る](/docs/ja-jp/get-started/architecture-scenarios/mobile-api/mobile-implementation-android#2-authorize-the-user)

<div id="get-the-credentials">
  ### 認証情報を取得する
</div>

認可 URL へのリクエストが成功すると、以下のレスポンスが返されます。

export const codeExample2 = `HTTP/1.1 302 Found
Location: https://{yourDomain}/callback?code=AUTHORIZATION_CODE`;

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

次に、レスポンスで返された`authorization_code`を、APIの呼び出しに使用できるアクセストークンと交換できます。以下のデータを含めて、[Token URL](https://auth0.com/docs/api/authentication#authorization-code-pkce-)に`POST`リクエストを送信します。

<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 code_verified=YOUR_GENERATED_CODE_VERIFIER \
    --data code=YOUR_AUTHORIZATION_CODE \
    --data 'redirect_uri=https://{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}&code_verified=YOUR_GENERATED_CODE_VERIFIER&code=YOUR_AUTHORIZATION_CODE&redirect_uri=https%3A%2F%2F{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}&code_verified=YOUR_GENERATED_CODE_VERIFIER&code=YOUR_AUTHORIZATION_CODE&redirect_uri=https%3A%2F%2F{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 response = Unirest.post("https://{yourDomain}/oauth/token")
    .header("content-type", "application/x-www-form-urlencoded")
    .body("grant_type=authorization_code&client_id={yourClientId}&code_verified=YOUR_GENERATED_CODE_VERIFIER&code=YOUR_AUTHORIZATION_CODE&redirect_uri=https%3A%2F%2F{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}',
      code_verified: 'YOUR_GENERATED_CODE_VERIFIER',
      code: 'YOUR_AUTHORIZATION_CODE',
      redirect_uri: 'https://{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}&code_verified=YOUR_GENERATED_CODE_VERIFIER&code=YOUR_AUTHORIZATION_CODE&redirect_uri=https%3A%2F%2F{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}&code_verified=YOUR_GENERATED_CODE_VERIFIER&code=YOUR_AUTHORIZATION_CODE&redirect_uri=https%3A%2F%2F{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}&code_verified=YOUR_GENERATED_CODE_VERIFIER&code=YOUR_AUTHORIZATION_CODE&redirect_uri=https%3A%2F%2F{https://yourApp/callback}"

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

| Parameter          | 説明                                                                                                                                                         |
| ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **grant\_type**    | `authorization_code` に設定する必要があります。                                                                                                                         |
| **client\_id**     | Auth0 Client Id の値です。[Auth0 Dashboard](https://manage.auth0.com/#/applications) の Application の Settings から確認できます。                                         |
| **code\_verifier** | [authorization URL](https://auth0.com/docs/api/authentication#authorization-code-grant-pkce-) (`/authorize`) に渡す `code_challenge` の生成に使用した、暗号学的にランダムなキーです。 |
| **code**           | 直前の authorize 呼び出しで受け取った `authorization_code` です。                                                                                                          |
| **redirect\_uri**  | この URL は、前のセクションで `/authorize` に渡した `redirect_uri` と一致している必要があります。                                                                                         |

Token URL からのレスポンスには、次が含まれます。

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

* **access\_token**: `audience` で指定した API のアクセストークン。
* **refresh\_token**: [Refresh Token](/docs/ja-jp/secure/tokens/refresh-tokens) は、`offline_access` スコープを含め、さらに Dashboard で API の **Allow Offline Access** を有効にした場合にのみ含まれます。
* **id\_token**: ユーザープロフィール情報を含む <Tooltip tip="IDトークン: リソースへのアクセスではなく、クライアント自体のための認証情報。" cta="用語集を見る" href="/docs/ja-jp/glossary?term=ID+Token">IDトークン</Tooltip> JWT。
* **token\_type**: トークンの種類を示す文字列で、常に Bearer トークンです。
* **expires\_in**: アクセストークンの有効期限が切れるまでの秒数。

API の呼び出しやユーザープロフィールの取得に使うため、上記の認証情報をローカルストレージに保存する必要があります。

[Android での実装を見る](/docs/ja-jp/get-started/architecture-scenarios/mobile-api/mobile-implementation-android#store-credentials)。

<div id="get-the-user-profile">
  ### ユーザープロファイルを取得する
</div>

[ユーザープロファイル](https://auth0.com/docs/api/authentication?http#user-profile)を取得するには、モバイルアプリケーションで [JWTライブラリ](https://jwt.io/#libraries-io) のいずれかを使って [IDトークン](/docs/ja-jp/secure/tokens/id-tokens) をデコードできます。これは、トークンの[署名を検証する](/docs/ja-jp/secure/tokens/id-tokens/validate-id-tokens#verify-the-signature)ことと、[クレームを検証する](/docs/ja-jp/secure/tokens/id-tokens/validate-id-tokens#verify-the-claims)ことによって行います。IDトークンを検証した後は、ユーザー情報を含むペイロードにアクセスできます。

```json lines theme={null}
{
  "email_verified": false,
  "email": "test.account@userinfo.com",
  "clientID": "q2hnj2iu...",
  "updated_at": "2016-12-05T15:15:40.545Z",
  "name": "test.account@userinfo.com",
  "picture": "https://s.gravatar.com/avatar/dummy.png",
  "user_id": "auth0|58454...",
  "nickname": "test.account",
  "created_at": "2016-12-05T11:16:59.640Z",
  "sub": "auth0|58454..."
}
```

[Android での実装については、こちらを参照してください。](/docs/ja-jp/get-started/architecture-scenarios/mobile-api/mobile-implementation-android#3-get-the-user-profile)

<div id="display-ui-elements-conditionally-based-on-scope">
  ### スコープに基づいて UI 要素を条件付きで表示する
</div>

ユーザーの`scope`に応じて、特定の UI 要素を表示または非表示にしたい場合があります。ユーザーに発行されたスコープを確認するには、ユーザーの認証時に付与された`scope`を調べる必要があります。これはすべてのスコープを含む文字列であるため、この文字列に必要な`scope`が含まれているかどうかを確認し、その結果に基づいて特定の UI 要素を表示するかどうかを判断する必要があります。

[Android での実装を見る](/docs/ja-jp/get-started/architecture-scenarios/mobile-api/mobile-implementation-android#4-display-ui-elements-conditionally-based-on-scope)

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

API の保護されたリソースにアクセスするには、認証済みユーザーのアクセストークンを、その API に送信するリクエストに含める必要があります。これを行うには、`Bearer` スキームを使用して、`Authorization` ヘッダーにアクセストークンを指定します。

[Android での実装を見る。](/docs/ja-jp/get-started/architecture-scenarios/mobile-api/mobile-implementation-android#5-call-the-api)

<div id="renew-the-token">
  ### トークンを更新する
</div>

<Warning>
  Refresh Token には有効期限がないため、ユーザーを実質的に半永久的に認証済みの状態にしておくことができます。したがって、アプリケーションで安全に保管する必要があります。Refresh Token が漏えいした場合や不要になった場合は、[Authentication API](https://auth0.com/docs/api/authentication#revoke-refresh-token) を使用して失効できます。
</Warning>

アクセストークン を更新するには、認可結果に含まれる <Tooltip tip="Refresh Token: ユーザーに再度ログインを求めることなく、新しい アクセストークン を取得するために使用するトークン。" cta="用語集を見る" href="/docs/ja-jp/glossary?term=Refresh+Token">Refresh Token</Tooltip> を使用して、`/oauth/token` エンドポイントに `POST` リクエストを送信します。

[Refresh Token](/docs/ja-jp/secure/tokens/refresh-tokens) が含まれるのは、前回の認可リクエストに `offline_access` スコープを含め、Auth0 Dashboard で API に対して **Allow Offline Access** を有効にしている場合のみです。

リクエストには次を含める必要があります。

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

  ```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");
  IRestResponse response = client.Execute(request);
  ```

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

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

  func main() {

  	url := "https://{yourDomain}/oauth/token"

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

  	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")
    .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'}
  };

  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_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("")

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

  conn.request("POST", "/{yourDomain}/oauth/token", headers=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'

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

| パラメータ              | 説明                                                                                                              |
| ------------------ | --------------------------------------------------------------------------------------------------------------- |
| **grant\_type**    | `refresh_token` に設定する必要があります。                                                                                   |
| **client\_id**     | Auth0 Client Id の値です。[Auth0 Dashboard](https://manage.auth0.com/#/applications) の アプリケーション の Settings から取得できます。 |
| **refresh\_token** | 前回の認証結果に含まれる Refresh Token です。                                                                                  |

レスポンスには、新しい アクセストークン が含まれます。

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

[Android での実装はこちらをご覧ください。](/docs/ja-jp/get-started/architecture-scenarios/mobile-api/mobile-implementation-android#store-the-credentials)
