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

> Mobile + 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) + "*****マスク済み*****";
          }
          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](/ja/docs/get-started/architecture-scenarios/mobile-api/api-implementation-nodejs#1-define-the-api-endpoints) を参照してください。

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

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

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

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

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  [JWT.io](https://jwt.io/) には、JWT の解析、署名の検証、クレームの検証といった処理の大部分を実行できるライブラリの一覧があります。
</Callout>

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

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

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

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

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

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

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

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

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

[Android での実装を参照してください。](/ja/docs/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)](/ja/docs/get-started/authentication-and-authorization-flow/authorization-code-flow-with-pkce/call-your-api-using-the-authorization-code-flow-with-pkce) を実装します。モバイルアプリケーションはまず、`code_challenge` とその生成に使用したメソッドを付けて、ユーザーを [認可 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 のクライアントIDの値です。[Auth0 Dashboard](https://manage.auth0.com/#/applications) の Application の Settings から取得できます。                                                                                                                                                                                                                                                        |
| **audience**                | API Identifier の値です。[Auth0 Dashboard](https://manage.auth0.com/#/apis) の API の Settings から取得できます。                                                                                                                                                                                                                                                                        |
| **scope**                   | IDトークンとアクセストークンで返されるクレームを決定する[スコープ](/ja/docs/get-started/apis/scopes)です。たとえば、`openid` スコープを指定すると、レスポンスに IDトークン が含まれます。このモバイルアプリの例では、次のスコープを使用します: `create:timesheets read:timesheets openid profile email offline_access`。これらのスコープにより、モバイルアプリは API を呼び出し、[リフレッシュトークン](/ja/docs/glossary?term=Refresh+Token) を取得し、IDトークンでユーザーの `name`、`picture`、`email` クレームを受け取ることができます。 |
| **response\_type**          | 使用する認証フローを示します。PKCE を使用するモバイルアプリケーションでは、`code` に設定する必要があります。                                                                                                                                                                                                                                                                                                             |
| **code\_challenge**         | code verifier から生成した code challenge です。code challenge の生成手順は[こちら](/ja/docs/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) で有効なコールバック URL として設定する必要があります。                                                                                                                                                                                   |

[Android での実装を参照してください。](/ja/docs/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 の呼び出しに使用できるアクセストークンと交換できます。以下のデータを含めて、[トークン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_NONE

  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>

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

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

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

[Android での実装を見る](/ja/docs/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トークン](/ja/docs/secure/tokens/id-tokens) をデコードできます。これを行うには、トークンの[署名を検証](/ja/docs/secure/tokens/id-tokens/validate-id-tokens#verify-the-signature)し、[クレームを検証](/ja/docs/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 での実装を確認してください。](/ja/docs/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`はすべてのスコープを含む文字列であるため、必要な`scope`が含まれているかを確認し、その結果に応じて特定の UI 要素を表示するかどうかを判断します。

[Android での実装を参照](/ja/docs/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 に送信するリクエストに含める必要があります。これを行うには、`Authorization` ヘッダーで `Bearer` スキームを使用してアクセストークンを送信します。

[Android での実装を参照してください。](/ja/docs/get-started/architecture-scenarios/mobile-api/mobile-implementation-android#5-call-the-api)

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

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

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

[リフレッシュトークン](/ja/docs/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_NONE

  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 のクライアントIDの値です。[Auth0 Dashboard](https://manage.auth0.com/#/applications) のアプリケーション設定から取得できます。 |
| **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 での実装については、こちらを参照してください。](/ja/docs/get-started/architecture-scenarios/mobile-api/mobile-implementation-android#store-the-credentials)
