> ## Documentation Index
> Fetch the complete documentation index at: https://docs-dev-eval-flywheel-swift-quickstart.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# PKCEを使った認可コードフローで独自のAPIを呼び出し

> Proof Key for Code Exchange（PKCE）を使用した認可コードフローを使用して、ネイティブやモバイル、シングルページのアプリケーションから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">
  このチュートリアルでは、PKCEを使った認可コードフローを用いて、ネイティブやモバイル、シングルページのアプリから独自のAPIを呼び出します。フローの仕組みやメリットについては、「[Proof Key for Code Exchange（PKCE）を使った認可コードフロー](/docs/ja-jp/get-started/authentication-and-authorization-flow/authorization-code-flow-with-pkce)」をお読みください。ネイティブやモバイル、シングルページのアプリケーションにログインを追加する方法については、「[PKCEを使った認可コードフローを使用してログインを追加する](/docs/ja-jp/get-started/authentication-and-authorization-flow/authorization-code-flow-with-pkce/add-login-using-the-authorization-code-flow-with-pkce)」をお読みください。
</Callout>

Auth0を使用すると、以下を使用して簡単にアプリでProof Key for Code Exchange（PKCE）を使用した認可コードフローを実装することができます。

* [Auth0 Mobile SDK](/docs/ja-jp/libraries)と[Auth0 Single-Page App SDK](/docs/ja-jp/libraries/auth0-single-page-app-sdk)：フローを実装する最も簡単な方法です。難しくて手間がかかる作業のほとんどが処理されます。[Mobile Quickstarts](/docs/ja-jp/quickstart/native)と[Single-Page App Quickstarts](/docs/ja-jp/quickstart/spa)でこのプロセスについて説明しています。
* [認証API](/docs/ja-jp/api/authentication)：独自のソリューションを構築したい場合は、このまま読み続けて、APIを直接呼び出す方法を学習してください。

## 前提条件

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

* [Auth0にアプリケーションを登録します](/docs/ja-jp/get-started/auth0-overview/create-applications/native-apps)。

  * アプリケーションタイプに応じて、**［Native（ネイティブ）］** または **［Single-Page App（シングルページアプリ）］** の **［Application Type（アプリケーションタイプ）］** を選択します。
  * `{yourCallbackUrl}`の **［Allowed Callback URL（許可されているコールバックURL）］** を追加します。コールバックURLの形式は、使用しているアプリケーションタイプとプラットフォームによって異なります。アプリケーションタイプの形式とプラットフォームの詳細については、「[Mobile/Native Quickstarts](/docs/ja-jp/quickstart/native)」と「[Single-Page App Quickstarts](/docs/ja-jp/quickstart/spa)」を参照してください。
  * アプリケーションの **［Grant Types（付与タイプ）］** に **［Authorization Code（認可コード）］** が必ず含まれていることを確認してください。詳細については、「[付与タイプを更新する](/docs/ja-jp/get-started/applications/update-grant-types)」をお読みください。
  * アプリケーションでリフレッシュトークンを使用できるようにするには、アプリケーションの **［Grant Types（付与タイプ）］** に **［Refresh Token（リフレッシュトークン）］** が含まれていることを確認してください。詳細については、「[付与タイプを更新する](/docs/ja-jp/get-started/applications/update-grant-types)」をお読みください。リフレッシュトークンの詳細については、「[リフレッシュトークン](/docs/ja-jp/secure/tokens/refresh-tokens)」をお読みください。
* [APIをAuth0に登録する](/docs/ja-jp/architecture-scenarios/mobile-api/part-2#create-the-api)

  * APIがリフレッシュトークンを受信して、以前のトークンの有効期限が切れたときに新しいトークンを取得できるようにする場合は、**［Allow Offline Access（オフラインアクセスの許可）］** を有効にします。

## ステップ

1. [Code verifier（コード検証）を作成する](#create-code-verifier)：
   トークンを要求するためにAuth0に送信される`code_verifier`を生成します。
2. [コードチャレンジを作成する](#create-code-challenge)：
   `authorization_code`を要求するためにAuth0に送信される`code_verifier`から`code_challenge`を生成します。
3. [ユーザーを認可する](#authorize-user)：
   ユーザーの認可を要求すると、`authorization_code`でアプリにリダイレクトされます。
4. [トークンを要求する](#request-tokens)：
   `authorization_code`と`code_verifier`をトークンと交換します。
5. [APIを呼び出す](#call-api)：
   取得したアクセストークンを使ってAPIを呼び出します。
6. [リフレッシュトークン](#refresh-tokens)：
   既存のトークンが期限切れになったら、リフレッシュトークンを使用して新しいトークンを要求します。

任意：[サンプルユースケースを参考にしてください](#sample-use-cases)。

### コードベリファイアを作成する

`code_verifier`を作成します。これは、トークンを要求するために最終的にAuth0に送信される、暗号的にランダムなBase64でエンコードされたキーです。

#### Javascriptのサンプル

```javascript lines theme={null}
// Dependency: Node.js crypto module
// https://nodejs.org/api/crypto.html#crypto_crypto
function base64URLEncode(str) {
    return str.toString('base64')
        .replace(/\+/g, '-')
        .replace(/\//g, '_')
        .replace(/=/g, '');
}
var verifier = base64URLEncode(crypto.randomBytes(32));
```

#### Javaのサンプル

```java lines theme={null}
// Dependency: Apache Commons Codec
// https://commons.apache.org/proper/commons-codec/
// Import the Base64 class.
// import org.apache.commons.codec.binary.Base64;
SecureRandom sr = new SecureRandom();
byte[] code = new byte[32];
sr.nextBytes(code);
String verifier = Base64.getUrlEncoder().withoutPadding().encodeToString(code);
```

#### Androidのサンプル

```java lines theme={null}
// See https://developer.android.com/reference/android/util/Base64
// Import the Base64 class
// import android.util.Base64;
SecureRandom sr = new SecureRandom();
byte[] code = new byte[32];
sr.nextBytes(code);
String verifier = Base64.encodeToString(code, Base64.URL_SAFE | Base64.NO_WRAP | Base64.NO_PADDING);
```

#### Swift 5のサンプル

```swift lines theme={null}
var buffer = [UInt8](repeating: 0, count: 32)
_ = SecRandomCopyBytes(kSecRandomDefault, buffer.count, &buffer)
let verifier = Data(buffer).base64EncodedString()
    .replacingOccurrences(of: "+", with: "-")
    .replacingOccurrences(of: "/", with: "_")
    .replacingOccurrences(of: "=", with: "")
```

#### Objective-Cのサンプル

```objective-c lines theme={null}
NSMutableData *data = [NSMutableData dataWithLength:32];
int result __attribute__((unused)) = SecRandomCopyBytes(kSecRandomDefault, 32, data.mutableBytes);
NSString *verifier = [[[[data base64EncodedStringWithOptions:0]
                        stringByReplacingOccurrencesOfString:@"+" withString:@"-"]
                        stringByReplacingOccurrencesOfString:@"/" withString:@"_"]
                        stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"="]];
```

### コードチャレンジを作成する

`authorization_code`を要求するためにAuth0に送信される`code_verifier`から`code_challenge`を生成します。

#### Javascriptのサンプル

```javascript lines theme={null}
// Dependency: Node.js crypto module
// https://nodejs.org/api/crypto.html#crypto_crypto
function sha256(buffer) {
    return crypto.createHash('sha256').update(buffer).digest();
}
var challenge = base64URLEncode(sha256(verifier));
```

#### Javaのサンプル

```java lines theme={null}
// Dependency: Apache Commons Codec
// https://commons.apache.org/proper/commons-codec/
// Import the Base64 class.
// import org.apache.commons.codec.binary.Base64;
byte[] bytes = verifier.getBytes("US-ASCII");
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(bytes, 0, bytes.length);
byte[] digest = md.digest();
String challenge = Base64.encodeBase64URLSafeString(digest);
```

#### Swift 5のサンプル

```swift lines theme={null}
import CommonCrypto

// ...

guard let data = verifier.data(using: .utf8) else { return nil }
var buffer = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
_ = data.withUnsafeBytes {
    CC_SHA256($0.baseAddress, CC_LONG(data.count), &buffer)
}
let hash = Data(buffer)
let challenge = hash.base64EncodedString()
    .replacingOccurrences(of: "+", with: "-")
    .replacingOccurrences(of: "/", with: "_")
    .replacingOccurrences(of: "=", with: "")
```

#### Objective-Cのサンプル

```objective-c lines theme={null}
// Dependency: Apple Common Crypto library
// http://opensource.apple.com//source/CommonCrypto
u_int8_t buffer[CC_SHA256_DIGEST_LENGTH * sizeof(u_int8_t)];
memset(buffer, 0x0, CC_SHA256_DIGEST_LENGTH);
NSData *data = [verifier dataUsingEncoding:NSUTF8StringEncoding];
CC_SHA256([data bytes], (CC_LONG)[data length], buffer);
NSData *hash = [NSData dataWithBytes:buffer length:CC_SHA256_DIGEST_LENGTH];
NSString *challenge = [[[[hash base64EncodedStringWithOptions:0]
                         stringByReplacingOccurrencesOfString:@"+" withString:@"-"]
                         stringByReplacingOccurrencesOfString:@"/" withString:@"_"]
                         stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"="]];
```

### ユーザーを認可する

`code_verifier`と`code_challenge`を作成したら、ユーザーの認可を取得する必要があります。技術的には、これが認可フローの始まりとなります。この手順には以下のようなプロセスが含まれます：

\* ユーザーを認証する。
\* 認証を行うために、ユーザーをIDプロバイダーへリダイレクトする。
\* アクティブな[シングルサインオン（SSO）](/docs/ja-jp/authenticate/single-sign-on)セッションを確認する。
\* 以前に同意を得ていない場合は、要求された権限レベルについてユーザーの同意を得る。

ユーザーを認可するために、アプリは前のステップで生成した`code_challenge`と`code_challenge`の生成に使用したメソッドを含め、ユーザーを[認可URL](/docs/ja-jp/api/authentication#authorization-code-grant-pkce-)に送信する必要があります。

#### 認可URLの例

export const codeExample1 = `https://{yourDomain}/authorize?
    response_type=code&
    code_challenge={codeChallenge}&
    code_challenge_method=S256&
    client_id={yourClientId}&
    redirect_uri={yourCallbackUrl}&
    scope=SCOPE&
    audience={apiAudience}&
    state={state}`;

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

##### パラメーター

ユーザーを認可するためにカスタムのAPIを呼び出すときは、

* オーディエンスパラメーターを含めなければなりません。
* ターゲットAPIでサポートされている追加のスコープを含めることができます。

| パラメーター名                 | 説明                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `response_type`         | Auth0が返す資格情報の種類（`code`または`token`）を示します。このフローでは、値は`code`である必要があります。                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `code_challenge`        | `code_verifier`から生成されたチャレンジ。                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `code_challenge_method` | チャレンジを生成するために使用されるメソッド（例：S256）。PKCE仕様では、`S256`と`plain`の2つのメソッドが定義されています。この例では前者が使用され、後者は推奨されていないため、Auth0でサポートされている**唯一**のメソッドです。                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| `client_id`             | アプリケーションのクライアントID。この値は、[［Application Settings（アプリケーション設定）］](https://manage.auth0.com/#/Applications/\{yourClientId}/settings)で確認できます。                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| `redirect_uri`          | ユーザーによって認可が付与された後にAuth0がブラウザーをリダイレクトするURL。認可コードは、`code` URLパラメーターで利用できます。このURLを[［Application Settings（アプリケーション設定）］](https://manage.auth0.com/#/Applications/\{yourClientId}/settings)で有効なコールバックURLとして指定する必要があります。<br /><br />**警告：** [OAuth 2.0仕様](https://tools.ietf.org/html/rfc6749#section-3.1.2)に従って、Auth0はハッシュの後のすべてを削除し、フラグメントを受け付け*ません*。                                                                                                                                                                                                                              |
| `scope`                 | 認可を要求する[スコープ](/docs/ja-jp/scopes)。これらはスペースで区切る必要があります。`profile`や`email`などのユーザーに関する[標準OpenID Connect（OIDC）スコープ](https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims)、[名前空間形式](/docs/ja-jp/tokens/guides/create-namespaced-custom-claims)に準拠した[カスタムクレーム](/docs/ja-jp/tokens/concepts/jwt-claims#custom-claims)、またはターゲットAPIでサポートされているあらゆるスコープ（例：`read:contacts`）を要求できます。リフレッシュトークンを取得するには、`offline_access`を含めます（[［Application Settings（アプリケーション設定）］](https://manage.auth0.com/#/apis)で\_\_［Allow Offline Access（オフラインアクセスを許可する）］\_\_フィールドが有効になっていることを確認してください）。 |
| `audience`              | WebアプリがアクセスするAPIの一意の識別子。このチュートリアルの前提条件の一部として作成したAPIの[［Settings（設定）］](https://manage.auth0.com/#/apis)タブの**Identifier（識別子）** 値を使用します。                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| `state`                 | （推奨）Auth0がリダイレクトしてアプリケーションに戻る際に含まれ、アプリが初期要求に追加する不透明な任意の英数字の文字列。この値を使用してクロスサイトリクエストフォージェリ（CSRF）攻撃を防ぐ方法については、[状態パラメーターを使用してCSRF攻撃を軽減する](/docs/ja-jp/protocols/oauth2/mitigate-csrf-attacks)を参照してください。                                                                                                                                                                                                                                                                                                                                                                           |
| `organization`          | （任意）ユーザーを認証するときに使用する組織のID。指定しない場合、アプリケーションが**Display Organization Prompt（組織のプロンプトを表示）** に設定されていると、ユーザーは認証時に組織名を入力できます。                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `invitation`            | （任意）組織の招待のチケットID。[Organizationにメンバーを招待](/docs/ja-jp/organizations/invite-members)する場合、ユーザーが招待を承諾したときに、アプリケーションは`invitation`および`organization`キー/値ペアを転送して招待の受け入れを処理する必要があります。                                                                                                                                                                                                                                                                                                                                                                                                   |

たとえば、APIを呼び出す際の認可URLのHTMLスニペットは、以下のようになります。

export const codeExample2 = `<a href="https://{yourDomain}/authorize?
  response_type=code&
  client_id={yourClientId}&
  code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM&
  code_challenge_method=S256&
  redirect_uri={yourCallbackUrl}&
  scope=appointments%20contacts&
  audience=appointments:api&
  state=xyzABC123">
  Sign In
</a>`;

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

#### 応答

すべてが成功すると`、HTTP 302`応答を受け取ります。認可コードはURLの末尾に含まれます：

```lines theme={null}
HTTP/1.1 302 Found
Location: {yourCallbackUrl}?code={authorizationCode}&state=xyzABC123
```

### トークンを要求する

取得した認可コードは、トークンと交換する必要があります。前の手順で抽出した認可コード（`code`）を使用して、`code_verifier`とともに送信する[トークンURL](/docs/ja-jp/api/authentication#authorization-code-pkce-)に`POST`する必要があります。

#### トークンURLへの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_verifier={yourGeneratedCodeVerifier}' \
    --data 'code={yourAuthorizationCode}' \
    --data 'redirect_uri={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_verifier=%7ByourGeneratedCodeVerifier%7D&code=%7ByourAuthorizationCode%7D&redirect_uri={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_verifier=%7ByourGeneratedCodeVerifier%7D&code=%7ByourAuthorizationCode%7D&redirect_uri={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_verifier=%7ByourGeneratedCodeVerifier%7D&code=%7ByourAuthorizationCode%7D&redirect_uri={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_verifier: '{yourGeneratedCodeVerifier}',
      code: '{yourAuthorizationCode}',
      redirect_uri: '{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_verifier={yourGeneratedCodeVerifier}" dataUsingEncoding:NSUTF8StringEncoding]];
  [postData appendData:[@"&code={yourAuthorizationCode}" dataUsingEncoding:NSUTF8StringEncoding]];
  [postData appendData:[@"&redirect_uri={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_verifier=%7ByourGeneratedCodeVerifier%7D&code=%7ByourAuthorizationCode%7D&redirect_uri={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_verifier=%7ByourGeneratedCodeVerifier%7D&code=%7ByourAuthorizationCode%7D&redirect_uri={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_verifier=%7ByourGeneratedCodeVerifier%7D&code=%7ByourAuthorizationCode%7D&redirect_uri={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_verifier={yourGeneratedCodeVerifier}".data(using: String.Encoding.utf8)!)
  postData.append("&code={yourAuthorizationCode}".data(using: String.Encoding.utf8)!)
  postData.append("&redirect_uri={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`に設定します。                                                                                                        |
| `code_verifier` | 暗号的にランダムなキーです。このチュートリアルの最初の手順で生成しました。                                                                                                 |
| `code`          | このチュートリアルの前の手順で取得した`authorization_code`です。                                                                                            |
| `client_id`     | アプリケーションのクライアントIDです。この値は[［Application Settings（アプリケーションの設定）］](https://manage.auth0.com/#/Applications/\{yourClientId}/settings)にあります。 |
| `redirect_uri`  | アプリケーションの設定で指定されている有効なコールバックURLです。このチュートリアルの前の手順で認可URLに渡された`redirect_uri`と完全に一致しなければなりません。これは、URLエンコードする必要があります。                      |

#### 応答

すべてが成功すると、`access_token`、`refresh_token`、`id_token`、および`token_type`の値を含むペイロードとともに、HTTP 200の応答を受信します。

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

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

[IDトークン](/docs/ja-jp/secure/tokens/id-tokens)には、デコードして抽出する必要があるユーザー情報が含まれています。

[アクセストークン](/docs/ja-jp/secure/tokens/access-tokens)は、[Auth0認証APIの/userinfoエンドポイント](/docs/ja-jp/api/authentication#get-user-info)または別のAPIを呼び出すために使用されます。独自のAPIを呼び出す場合にAPIが最初に行うのは、[アクセストークンを検証](/docs/ja-jp/secure/tokens/access-tokens/validate-access-tokens)することです。

[リフレッシュトークン](/docs/ja-jp/secure/tokens/refresh-tokens)は、アクセストークンまたはIDトークンの期限が切れたときに、新しいトークンの取得に使用されます。`refresh_token`は、`offline_access`スコープを含め、DashboardでAPIの\*\*［Allow Offline Access（オフラインアクセスの許可）］\*\* を有効にした場合にのみ、応答内に表示されます。

<Warning>
  リフレッシュトークンは、ユーザーが実質的に永久に認証された状態を維持できるようにするため、安全に保管しなければなりません。
</Warning>

### APIを呼び出す

ネイティブ/モバイルアプリケーションからAPIを呼び出すには、アプリケーションは、取得したアクセストークンをBearerトークンとしてHTTP要求の認証ヘッダーで渡さなければなりません。

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

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

  NSDictionary *headers = @{ @"content-type": @"application/json",
                             @"authorization": @"Bearer {accessToken}" };

  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://myapi.com/api"]
                                                         cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                     timeoutInterval:10.0];
  [request setHTTPMethod:@"GET"];
  [request setAllHTTPHeaderFields:headers];

  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 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_NONE

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

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

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

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

  let request = NSMutableURLRequest(url: NSURL(string: "https://myapi.com/api")! as URL,
                                          cachePolicy: .useProtocolCachePolicy,
                                      timeoutInterval: 10.0)
  request.httpMethod = "GET"
  request.allHTTPHeaderFields = headers

  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>

### リフレッシュトークン

このチュートリアルに従って次の作業を完了している場合、あなたはすでに[リフレッシュ トークン](/docs/ja-jp/secure/tokens/refresh-tokens)を受け取っています。

* オフラインアクセスを許可するように、APIを構成する。
* [認可エンドポイント](/docs/ja-jp/api/authentication/reference#authorize-application)を通じて認証要求を開始するときに、`offline_access`スコープを含める。

リフレッシュトークンを使って新しいアクセストークンを取得することができます。通常、新しいアクセストークンが必要になるのは、以前のトークンの期限が切れたときや、新しいリソースに初めてアクセスする場合に限られます。APIを呼び出すたびにエンドポイントを呼び出して新しいアクセストークンを取得するのは、良くない習慣です。Auth0は、同じIPから同じトークンを使って実行できるエンドポイントへの要求数を、レート制限を通じて調整します。

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

#### トークンURLへの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=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);
  });
  ```

  ```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=refresh_token" dataUsingEncoding:NSUTF8StringEncoding]];
  [postData appendData:[@"&client_id={yourClientId}" dataUsingEncoding:NSUTF8StringEncoding]];
  [postData appendData:[@"&refresh_token={yourRefreshToken}" 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=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_NONE

  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
  ```

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

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

  let postData = NSMutableData(data: "grant_type=refresh_token".data(using: String.Encoding.utf8)!)
  postData.append("&client_id={yourClientId}".data(using: String.Encoding.utf8)!)
  postData.append("&refresh_token={yourRefreshToken}".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`     | アプリケーションのクライアントID。この値は[アプリケーション設定](https://manage.auth0.com/#/Applications/\{yourClientId}/settings)で確認できます。 |
| `refresh_token` | 使用するリフレッシュトークン。                                                                                              |
| `scope`         | （任意）要求されたスコープの権限をスペースで区切ったリスト。送信されない場合は、元のスコープが使用されます。送信する場合は、スコープを減らして要求することができます。これはURLでエンコードされている必要があります。 |

#### 応答

すべてが成功すると、新しい`access_token`、秒単位の有効期間（`expires_in`）、付与された`scope`値、および`token_type`を含むペイロードとともに`HTTP 200`応答を受信します。最初のトークンのスコープに`openid`が含まれている場合、応答には新しい`id_token`も含まれます。

```json lines theme={null}
{
  "access_token": "eyJ...MoQ",
  "expires_in": 86400,
  "scope": "openid offline_access",
  "id_token": "eyJ...0NE",
  "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>

### サンプルユースケース

#### トークンをカスタマイズする

ルールを使用して、アクセストークンで返されたスコープを変更し、クレームをアクセスとIDトークンに追加することができます。（ルールの詳細については、「[Auth0ルール](/docs/ja-jp/customize/rules)」をお読みください。）これを行うには、ユーザーの認証後に実行される次のルールを追加します。

```javascript lines theme={null}
exports.onExecutePostLogin = async (event, api) => {
  // Add custom claims to Access Token and ID Token
  api.accessToken.setCustomClaim('https://foo/bar', 'value');
  api.idToken.setCustomClaim('https://fiz/baz', 'some other value');

  // Modify the scope of the Access Token
  api.accessToken.addScope('foo');
  api.accessToken.addScope('bar');
};
```

すべてのルールが実行された後、トークンでスコープが使用可能になります。

<Warning>
  Auth0は、プロファイル情報を[OpenID Connect（OIDC）仕様](https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims)で定義されている構造化クレーム形式で返します。つまり、IDトークンまたはアクセストークンに追加するカスタムクレームは、衝突を避けるために[ガイドラインと制限に従わなければなりません](/docs/ja-jp/secure/tokens/json-web-tokens/create-custom-claims)。
</Warning>

#### サンプルアプリケーションを表示する：モバイルアプリ + API

サンプル実装の場合、[モバイル + API](/docs/ja-jp/architecture-scenarios/application/mobile-api)アーキテクチャのシナリオを参照してください。この一連のチュートリアルには、付録に[GitHubで提供されているコードのサンプル](https://github.com/auth0-samples/auth0-pnp-exampleco-timesheets)があります。

## もっと詳しく

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