> ## Documentation Index
> Fetch the complete documentation index at: https://auth0.com/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>

## APIエンドポイントの定義

まず、APIのエンドポイントを定義する必要があります。

<Card title="APIエンドポイントとは">
  **APIエンドポイントは**

  たとえば、レストランAPIには`/orders`や`/customers`などのエンドポイントがあるかもしれません。このAPIに接続するアプリケーションは、関連するHTTPメソッド（`POST`、`GET`、`PUT`、`PATCH`、`DELETE`）を使ってAPIエンドポイントを呼び出すことにより、CRUD操作（作成、読み取り、更新、削除）を実行することができます。
</Card>

この実装では、2つのエンドポイントのみ定義します。1つは従業員の全タイムシートのリストを取得するため、もう1つは従業員がタイムシートエントリーを新規作成できるようにするためのものです。

`/timesheets`エンドポイントへの`HTTP GET`要求は、ユーザーがタイムシートを取得できるようにし、`/timesheets`への`HTTP POST`要求は、ユーザーが新たなタイムシートを追加できるようにします。

[Node.js](https://auth0.com/docs/architecture-scenarios/application/mobile-api/api-implementation-nodejs#1-define-the-api-endpoints)

### エンドポイントのセキュリティ確保

APIがヘッダーの一部にBearerアクセストークンのある要求を受け取った場合、最初にすべきことはトークンの検証です。これは複数の手順で構成され、そのうち1つでも失敗した場合、要求は、`Missing or invalid token`という呼び出し元アプリへのエラーメッセージとともに拒否されなければなりません。

APIは以下の検証を実行すべきです。

* <Tooltip data-tooltip-id="react-containers-DefinitionTooltip-3" href="/docs/ja-jp/glossary?term=json-web-token" tip="JSON Web Token（JWT）: 二者間のクレームを安全に表現するために使用される標準IDトークン形式（および多くの場合、アクセストークン形式）。" cta="用語集の表示">JWT</Tooltip>が整形式であることを確認する
* 署名を確認する
* 標準クレームを検証する

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  [JWT.io](https://jwt.io/)は、JWTの解析から署名・クレームの検証まで、ほとんどの作業に役立つライブラリーのリストを提供します。
</Callout>

検証プロセスにはクライアント権限（スコープ）の確認も含まれますが、これに関しては次の段落で別に説明します。

アクセストークン検証の詳細については、[「アクセストークンを検証する」](https://auth0.com/docs/tokens/guides/validate-access-tokens)を参照してください。

[Node.js](https://auth0.com/docs/architecture-scenarios/application/mobile-api/api-implementation-nodejs#2-secure-the-api-endpoints)

### クライアントの権限の確認

この段階ではJWTの有効性が検証されています。最後の手順は、クライアントが保護されたリソースにアクセスするために必要な権限を持っているかどうかを検証することです。

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

[Node.js](https://auth0.com/docs/architecture-scenarios/application/mobile-api/api-implementation-nodejs#3-check-the-client-permissions)

### ユーザーIDの判断

どちらのエンドポイント（タイムシートのリスト取得用と新規タイムシート追加用）でも、ユーザーのIDを判断する必要があります。

これは、タイムシートのリスト取得に関しては、要求元のユーザーのタイムシートのみを返すようにするためです。一方の新規タイムシートの追加に関しては、タイムシートがその要求元のユーザーと関連付けられていることを確認するためです。

標準JWTクレームの1つは、クレームの対象である本人を識別する`sub`クレームです。暗黙的付与フローの場合、このクレームにはAuth0ユーザーの一意の識別子であるIDが含まれます。これを使って、外部システムのいかなる情報でも、特定ユーザーに関連付けることができます。

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

[Node.js](https://auth0.com/docs/architecture-scenarios/application/mobile-api/api-implementation-nodejs#4-determine-the-user-identity)

## モバイルアプリの実装

このセクションでは、当社シナリオでモバイルアプリケーションを実装する方法を説明します。

[Androidでの実装を参照してください。](https://auth0.com/docs/architecture-scenarios/application/mobile-api/mobile-implementation-android#1-set-up-the-application)

### ユーザーの認可

ユーザーを認可するには、[Proof Key for Code Exchange（PKCE）での認可コードフロー](https://auth0.com/docs/flows/guides/auth-code-pkce/call-api-auth-code-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="text" lines />

認可URLへの`GET`要求は、以下の値を含める必要があります。

| パラメーター                      | 説明                                                                                                                                                                                                                                                                                                    |
| --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **client\_id**              | Auth0クライアントIDの値です。[Auth0 Dashboard](https://manage.auth0.com/#/applications)にあるアプリケーションの設定から取得できます。                                                                                                                                                                                                   |
| **audience**                | API識別子の値です。[Auth0 Dashboard](https://manage.auth0.com/#/apis)にあるAPIの設定から取得できます。                                                                                                                                                                                                                       |
| **scope**                   | IDトークンとアクセストークンで返されるクレームを決定する[スコープ](/docs/ja-jp/scopes) です。たとえば、`openid`スコープではIDトークンが返されます。提供しているモバイルアプリの例では、次のスコープを使用しています：`create:timesheets read:timesheets openid profile email offline_access`。これらのスコープによって、モバイルアプリはAPIを呼び出し、リフレッシュトークンを取得して、IDトークンでユーザーの`name`、`picture`、`email`クレームを返すことができます。 |
| **response\_type**          | 使用する認証フローです。PKCEを使用するモバイルアプリケーションの場合は、これを`code`に設定します。                                                                                                                                                                                                                                                |
| **code\_challenge**         | コード検証が生成したコードチャレンジです。コードチャレンジの生成方法については、[こちら](/docs/ja-jp/flows/guides/auth-code-pkce/call-api-auth-code-pkce#authorize-the-user#create-a-code-verifier)を参照してください。                                                                                                                                    |
| **code\_challenge\_method** | チャレンジの生成方法です。Auth0は`S256`のみに対応しています。                                                                                                                                                                                                                                                                  |
| **redirect\_uri**           | ユーザーが認可された後に、Auth0がブラウザーをダイレクトするURLです。認可コードはURLパラメーターのcodeにあります。このURLは、有効なコールバックURLとして[アプリケーションの設定](https://manage.auth0.com/#/applications)で指定されなければなりません。                                                                                                                                           |

[Androidでの実装を参照してください。](https://auth0.com/docs/architecture-scenarios/application/mobile-api/mobile-implementation-android#2-authorize-the-user)

### 資格情報の取得

認可URLへの要求が成功したら、以下の応答を受け取ります。

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

<AuthCodeBlock children={codeExample2} language="text" lines />

次に、応答の`認可コード`をAPIを呼び出すのに使用するアクセストークンと交換します。以下のデータを含めて、[トークン URL](/docs/ja-jp/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);
  });
  ```

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

  NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" };

  NSMutableData *postData = [[NSMutableData alloc] initWithData:[@"grant_type=authorization_code" dataUsingEncoding:NSUTF8StringEncoding]];
  [postData appendData:[@"&client_id={yourClientId}" dataUsingEncoding:NSUTF8StringEncoding]];
  [postData appendData:[@"&code_verified=YOUR_GENERATED_CODE_VERIFIER" dataUsingEncoding:NSUTF8StringEncoding]];
  [postData appendData:[@"&code=YOUR_AUTHORIZATION_CODE" dataUsingEncoding:NSUTF8StringEncoding]];
  [postData appendData:[@"&redirect_uri=https://{https://yourApp/callback}" dataUsingEncoding:NSUTF8StringEncoding]];

  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://{yourDomain}/oauth/token"]
                                                         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/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
  ```

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

  let headers = ["content-type": "application/x-www-form-urlencoded"]

  let postData = NSMutableData(data: "grant_type=authorization_code".data(using: String.Encoding.utf8)!)
  postData.append("&client_id={yourClientId}".data(using: String.Encoding.utf8)!)
  postData.append("&code_verified=YOUR_GENERATED_CODE_VERIFIER".data(using: String.Encoding.utf8)!)
  postData.append("&code=YOUR_AUTHORIZATION_CODE".data(using: String.Encoding.utf8)!)
  postData.append("&redirect_uri=https://{https://yourApp/callback}".data(using: String.Encoding.utf8)!)

  let request = NSMutableURLRequest(url: NSURL(string: "https://{yourDomain}/oauth/token")! 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>

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

トークン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** :[リフレッシュトークン](/docs/ja-jp/tokens/concepts/refresh-tokens)は、`offline_access`スコープを含め、DashboardでAPIの\*\*［Allow Offline Access（オフラインアクセスの許可）］\*\* を有効にした場合にのみ表示されます。
* **id\_token** :ユーザープロファイル情報が入ったIDトークンJWT
* **token\_type** :トークンのタイプを含む文字列で、常にベアラートークンです。
* **expires\_in** :アクセストークンの有効期限が切れるまでの秒数。

APIの呼び出しとユーザープロファイルの取得に使用するために、上記の資格情報をローカルストレージに保存しておく必要があります。

[Androidでの実装を参照してください。](https://auth0.com/docs/architecture-scenarios/application/mobile-api/mobile-implementation-android#store-credentials)

### ユーザープロファイルの取得

[ユーザープロファイル](https://auth0.com/docs/api/authentication?http#user-profile)を取得するために、モバイルアプリケーションは[JWTライブラリー](https://jwt.io/#libraries-io)の１つを使用して、[IDトークン](https://auth0.com/docs/tokens/concepts/id-tokens)をデコードすることができます。これは、[署名を検証](https://auth0.com/docs/tokens/guides/validate-id-token#verify-the-signature)して、トークンの[クレームを検証](https://auth0.com/docs/tokens/guides/validate-id-token#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での実装を参照してください。](https://auth0.com/docs/architecture-scenarios/application/mobile-api/mobile-implementation-android#3-get-the-user-profile)

### スコープに基づいた条件付きUI要素の表示

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

[Androidでの実装を参照してください](https://auth0.com/docs/architecture-scenarios/application/mobile-api/mobile-implementation-android#4-display-ui-elements-conditionally-based-on-scope)

### APIの呼び出し

APIから安全なリソースにアクセスするには、認証されたユーザーのアクセストークンを、送信される要求に入れる必要があります。これには、`Bearer`スキームを使用して、`Authorization`ヘッダー内でアクセストークンを送る必要があります。

[Androidでの実装を参照してください。](https://auth0.com/docs/architecture-scenarios/application/mobile-api/mobile-implementation-android#5-call-the-api)

### トークンの更新

<Warning>
  リフレッシュトークンは、有効期限がなく、ユーザーに対し、実質的に永久に承認された状態でいることを可能にするため、アプリケーションで安全に保管されなければなりません。リフレッシュトークンが侵害された場合、または不要になった場合は、[Authentication API](/docs/ja-jp/api/authentication#revoke-refresh-token)を使用してリフレッシュトークンを取り消すことができます。
</Warning>

アクセストークンをリフレッシュするには、認可結果のリフレッシュトークンを使用して、`/oauth/token`エンドポイントへの`POST`要求を実行します。

[リフレッシュトークン](https://auth0.com/docs/tokens/concepts/refresh-tokens)は、`offline_access`スコープを先行の認可要求に含め、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);
  });
  ```

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

  NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" };

  NSData *postData = [[NSData alloc] initWithData:[@"undefined" dataUsingEncoding:NSUTF8StringEncoding]];

  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://{yourDomain}/oauth/token"]
                                                         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/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
  ```

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

  let headers = ["content-type": "application/x-www-form-urlencoded"]

  let postData = NSData(data: "undefined".data(using: String.Encoding.utf8)!)

  let request = NSMutableURLRequest(url: NSURL(string: "https://{yourDomain}/oauth/token")! 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>

| パラメーター             | 説明                                                                                                                             |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------ |
| **grant\_type**    | `refresh_token`に設定する必要があります。                                                                                                   |
| **client\_id**     | Auth0クライアントIDの値。これは[Auth0 Dashboard](https://manage.auth0.com/#/applications)にある［Application（アプリケーション）］の［Settings（設定）］で取得できます。 |
| **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での実装を参照してください。](https://auth0.com/docs/architecture-scenarios/application/mobile-api/mobile-implementation-android#store-the-credentials)
