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

> PKCE を使用する認可コードフローを使って、ネイティブ、モバイル、またはシングルページアプリケーションにログインを追加する方法を説明します。

# PKCE を使用する認可コードフローを使用してログインを追加する

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

ネイティブ、モバイル、またはシングルページアプリにログインを追加するには、PKCE を使用する認可コードフローを利用できます。このフローの仕組みと、これを使用すべき理由については、[Authorization Code Flow with Proof Key for Code Exchange (PKCE)](/ja/docs/get-started/authentication-and-authorization-flow/authorization-code-flow-with-pkce) を参照してください。ネイティブ、モバイル、またはシングルページアプリから API を呼び出す方法については、[Call Your API Using Authorization Code Flow with PKCE](/ja/docs/get-started/authentication-and-authorization-flow/authorization-code-flow-with-pkce/call-your-api-using-the-authorization-code-flow-with-pkce) を参照してください。

PKCE を使用する認可コードフローを実装するには、次のリソースを利用できます。

* [Auth0 Mobile SDKs](/ja/docs/libraries) と [Auth0 Single-Page App SDK](/ja/docs/libraries/auth0-single-page-app-sdk): フローを最も簡単に実装できる方法で、面倒な処理の大半を任せられます。[Mobile Quickstarts](/ja/docs/quickstart/native) と [Single-Page App クイックスタート](/ja/docs/quickstart/spa) では、手順を順を追って説明しています。
* [Authentication API](https://auth0.com/docs/api/authentication): 独自に実装したい場合は、このまま読み進めて API を直接呼び出す方法を確認してください。

ログインに成功すると、アプリケーションはユーザーの <Tooltip tip="IDトークン: リソースへのアクセスではなく、クライアント自体のための認証情報。" cta="用語集を表示" href="/ja/docs/glossary?term=ID+token">IDトークン</Tooltip> と <Tooltip tip="IDトークン: リソースへのアクセスではなく、クライアント自体のための認証情報。" cta="用語集を表示" href="/ja/docs/glossary?term=access+token">アクセストークン</Tooltip> にアクセスできるようになります。IDトークンには基本的なユーザープロフィール情報が含まれ、アクセストークンは Auth0 の `/userinfo` エンドポイントや独自の保護された API の呼び出しに使用できます。IDトークンの詳細については、[ID Tokens](/ja/docs/secure/tokens/id-tokens) を参照してください。アクセストークンの詳細については、[Access Tokens](/ja/docs/secure/tokens/access-tokens) を参照してください。

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

アプリを Auth0 に登録します。詳しくは、[ネイティブアプリケーションを登録する](/ja/docs/get-started/auth0-overview/create-applications/native-apps)または[シングルページ Web アプリケーションを登録する](/ja/docs/get-started/auth0-overview/create-applications/single-page-web-apps)を参照してください。

* アプリケーションの種類に応じて、**Application Type** で **Native** または **Single-Page App** を選択します。
* **Allowed Callback URL** に `YOUR_CALLBACK_URL` を追加します。コールバック URL の形式は、アプリケーションの種類とプラットフォームによって異なります。アプリケーションの種類およびプラットフォームごとの形式について詳しくは、[Native/Mobile クイックスタート](/ja/docs/quickstart/native)および[Single-Page App クイックスタート](/ja/docs/quickstart/spa)を参照してください。
* アプリケーションの **Grant Types** に **認可コード** が含まれていることを確認します。詳しくは、[Grant Types を更新する](/ja/docs/get-started/applications/update-grant-types)を参照してください。

<div id="create-code-verifier">
  ## code verifier を作成
</div>

`code_verifier` を作成します。これは、後でトークンをリクエストするために Auth0 に送信する、暗号学的にランダムな Base64 エンコード文字列です。

`code_verifier` の作成アルゴリズムの詳細については、<Tooltip tip="認可プロトコルとワークフローを定義する OAuth 2.0 の認可フレームワーク。" cta="用語集を表示" href="/ja/docs/glossary?term=OAuth">OAuth</Tooltip> Proof Key for Code Exchange 仕様のセクション [4.1 Client Creates a Code Verifier](https://datatracker.ietf.org/doc/html/rfc7636#section-4.1) を参照してください。

<div id="javascript-sample">
  ### Javascript のサンプル
</div>

```javascript lines theme={null}
// 依存関係: Node.js cryptoモジュール
// 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 の例

```javascript lines theme={null}
// 依存関係: Apache Commons Codec
// https://commons.apache.org/proper/commons-codec/
// Base64クラスをインポートします。
// 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);
```

<div id="android-sample">
  ### Android のサンプル
</div>

```javascript lines theme={null}
// 依存関係: Apache Commons Codec
// https://commons.apache.org/proper/commons-codec/
// Base64クラスをインポートします。
// import org.apache.commons.codec.binary.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);
```

<div id="swift-5-sample">
  ### Swift 5 のサンプル
</div>

```javascript 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: "")
```

<div id="objective-c-sample">
  ### Objective-C のサンプル
</div>

```objc 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:@"="]];
```

<div id="create-code-challenge">
  ## code チャレンジを作成
</div>

`authorization_code` をリクエストするために Auth0 に送信する `code_challenge` を、`code_verifier` から生成します。

`code_challenge` が `code_verifier` からどのように導出されるかについて詳しくは、OAuth Proof Key for Code Exchange 仕様のセクション [4.2 Client Creates the Code Challenge](https://datatracker.ietf.org/doc/html/rfc7636#section-4.) を参照してください。

### JavaScript のサンプル

```javascript lines theme={null}
// 依存関係: Node.js crypto モジュール
// https://nodejs.org/api/crypto.html#crypto_crypto
function sha256(buffer) {
    return crypto.createHash('sha256').update(buffer).digest();
}
var challenge = base64URLEncode(sha256(verifier));
```

<div id="java-sample">
  ### Java のサンプル
</div>

```java lines theme={null}
// 依存関係: Apache Commons Codec
// https://commons.apache.org/proper/commons-codec/
// Base64クラスをインポートします。
// 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: "")
```

<div id="objective-c-sample">
  ### Objective-C のサンプル
</div>

```objc lines theme={null}
// 依存関係: Apple Common Cryptoライブラリ
// 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:@"="]];
```

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

ユーザーに認可を求め、`authorization_code` を付けてアプリへリダイレクトして戻します。

`code_verifier` と `code_challenge` を作成したら、次にユーザーの認可を取得する必要があります。これは技術的には <Tooltip tip="認可フロー: OAuth 2.0 フレームワークで規定されている認可のグラント（またはワークフロー）。" cta="用語集を見る" href="/ja/docs/glossary?term=authorization+flow">認可フロー</Tooltip> の開始にあたり、このステップには次のプロセスのうち 1 つ以上が含まれる場合があります。

* ユーザーを認証する。
* 認証を処理するため、ユーザーを <Tooltip tip="IDプロバイダー（IdP）: デジタルアイデンティティを保存および管理するサービス。" cta="用語集を見る" href="/ja/docs/glossary?term=Identity+Provider">IDプロバイダー</Tooltip> にリダイレクトする。
* アクティブな [シングルサインオン (SSO) ](/ja/docs/authenticate/single-sign-on) セッションを確認する。
* 以前に同意が得られていない場合は、要求された権限レベルに対するユーザーの同意を取得する。

ユーザーを認可するには、アプリからユーザーを [認可 URL](https://auth0.com/docs/api/authentication#authorization-code-grant-pkce-) に送る必要があります。その際、前の手順で生成した `code_challenge` と、`code_challenge` の生成に使用したメソッドを含めます。

<div id="authorization-url-example">
  ### 認可 URL の例
</div>

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

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

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

| Parameter Name          | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `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 Specification](https://tools.ietf.org/html/rfc6749#section-3.1.2) に従い、Auth0 はハッシュ以降をすべて削除し、フラグメントは *一切* 考慮しません。                                                                                                                                                                                                                                                                                                                                                                                       |
| `scope`                 | 認可をリクエストする [スコープ](/ja/docs/get-started/apis/scopes) を指定します。これは、どのクレーム (またはユーザー属性) を返すかを決定します。各値はスペースで区切る必要があります。レスポンスで IDトークン を取得するには、少なくとも `openid` スコープを指定する必要があります。ユーザーの完全なユーザープロファイルを返したい場合は、`openid profile` をリクエストできます。`email` などの [標準 OpenID Connect (OIDC) スコープ](https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims) や、[名前空間付き形式](/ja/docs/secure/tokens/json-web-tokens/create-custom-claims) に準拠した [カスタムクレーム](/ja/docs/secure/tokens/json-web-tokens/json-web-token-claims#custom-claims) をリクエストできます。[リフレッシュトークン](/ja/docs/glossary?term=Refresh+Token) を取得するには `offline_access` を含めてください ([Application Settings](https://manage.auth0.com/#/applications) で **Allow Offline Access** フィールドが有効になっていることを確認してください) 。 |
| `state`                 | (推奨) アプリが初期リクエストに追加し、アプリケーションにリダイレクトするときに Auth0 が含める、不透明な任意の英数字文字列です。この値を使用して Cross-site Request Forgery (CSRF) 攻撃を防ぐ方法については、[Mitigate CSRF Attacks With State Parameters](/ja/docs/secure/attack-protection/state-parameters) を参照してください。                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `connection`            | (省略可) ユーザーに特定の接続を使ってサインインさせます。たとえば、`github` という値を渡すと、ユーザーは GitHub アカウントでログインするために直接 GitHub にリダイレクトされます。指定しない場合、ユーザーには設定済みのすべての接続を含む Auth0 Lock 画面が表示されます。設定済みの接続の一覧は、アプリケーションの **Connections** タブで確認できます。                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `organization`          | (省略可) ユーザーの認証時に使用する組織の ID です。指定しない場合、アプリケーションで **Display Organization Prompt** が有効になっていれば、ユーザーは認証時に組織名を入力できます。                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `invitation`            | (省略可) 組織招待のチケットIDです。[組織にメンバーを招待する](/ja/docs/manage-users/organizations/configure-organizations/invite-members) 場合、ユーザーが招待を承諾したときに、アプリケーションは `invitation` と `organization` のキーと値のペアを渡して、招待承諾を処理する必要があります。                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |

例として、アプリにログインを追加する際の認可 URL 用 HTML スニペットは次のようになります。

export const codeExample2 = `<a href="https://{yourDomain}/authorize?
  response_type=code&
  code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM&
  code_challenge_method=S256&
  client_id={yourClientId}&
  redirect_uri={yourCallbackUrl}&
  scope=openid%20profile&
  state=xyzABC123">
  サインイン
</a>`;

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

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

正常に処理されると、`HTTP 302` レスポンスが返されます。認可コードは URL の末尾に含まれます。

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

<div id="request-tokens">
  ## トークンを取得する
</div>

`authorization_code` と `code_verifier` をトークンに交換します。

認可コードを取得したら、それをトークンに交換する必要があります。前の手順で取得した認可コード (`code`) を使用して、`code_verifier` とともに [トークンURL](https://auth0.com/docs/api/authentication#authorization-code-pkce-) に `POST` リクエストを送信します。

<div id="post-to-token-url-example">
  ### トークンURLにPOSTする例
</div>

<AuthCodeGroup>
  ```bash cURL theme={null}
  curl --request POST \
    --url 'https://{yourDomain}/oauth/token' \
    --header 'content-type: application/x-www-form-urlencoded' \
    --data grant_type=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);
  });
  ```

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

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

| パラメーター名         | 説明                                                                                                                          |
| --------------- | --------------------------------------------------------------------------------------------------------------------------- |
| `grant_type`    | `"authorization_code"` に設定します。                                                                                              |
| `code_verifier` | このチュートリアルの最初の手順で生成した、暗号学的にランダムなキーです。                                                                                        |
| `code`          | このチュートリアルの前の手順で取得した `authorization_code` です。                                                                                |
| `client_id`     | アプリケーションのクライアントIDです。この値は [Application Settings](https://manage.auth0.com/#/Applications/\{yourClientId}/settings) で確認できます。  |
| `redirect_uri`  | Application Settings で設定した有効なコールバックURLです。これは、このチュートリアルの前の手順で認可 URL に渡した `redirect_uri` と完全に一致している必要があります。なお、URL エンコードが必要です。 |

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

正常に処理されると、`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トークンを検証する](/ja/docs/secure/tokens/id-tokens/validate-id-tokens)および[アクセストークンを検証する](/ja/docs/secure/tokens/access-tokens/validate-access-tokens)を参照してください。
</Warning>

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

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

[リフレッシュトークン](/ja/docs/secure/tokens/refresh-tokens)は、以前のアクセストークンまたは IDトークン の有効期限が切れた後に、新しいアクセストークンまたは IDトークン を取得するために使用されます。`refresh_token` がレスポンスに含まれるのは、`offline_access` スコープを指定し、Dashboard で API に対して **Allow Offline Access** を有効にした場合のみです。

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

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

<div id="basic-authentication-request">
  ### Basic認証リクエスト
</div>

この例は、手順 1 でユーザーを認証する際に送信できる最も基本的なリクエストを示しています。Auth0 のログイン画面が表示され、ユーザーは設定済みの任意の接続でサインインできます。

export const codeExample13 = `https://{yourDomain}/authorize?
    response_type=code&
    code_challenge={codeChallenge}&
    code_challenge_method=S256&
    client_id={yourClientId}&
    redirect_uri={yourCallbackUrl}&
    scope=openid`;

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

ここでトークンをリクエストすると、IDトークンには最も基本的なクレームが含まれます。IDトークンをデコードすると、次のようになります。

```json lines theme={null}
{
  "iss": "https://auth0pnp.auth0.com/",
  "sub": "auth0|581...",
  "aud": "xvt9...",
  "exp": 1478112929,
  "iat": 1478076929
}
```

<div id="request-users-name-and-profile-picture">
  ### ユーザーの名前とプロフィール画像をリクエストする
</div>

通常の認証に加えて、この例では、名前やプロフィール画像などの追加のユーザー情報をリクエストする方法を示します。

ユーザーの名前とプロフィール画像をリクエストするには、ユーザーの認可時に適切なスコープを追加する必要があります。

export const codeExample14 = `https://{yourDomain}/authorize?
    response_type=code&
    code_challenge={codeChallenge}&
    code_challenge_method=S256&
    client_id={yourClientId}&
    redirect_uri={yourCallbackUrl}&
    scope=openid%20name%20picture&
    state={state}`;

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

これで、トークンをリクエストすると、IDトークンに要求した`name`および`picture`クレームが含まれるようになります。IDトークンをデコードすると、次のようになります。

```json lines theme={null}
{
  "name": "auth0user@...",
  "picture": "https://example.com/profile-pic.png",
  "iss": "https://auth0user.auth0.com/",
  "sub": "auth0|581...",
  "aud": "xvt...",
  "exp": 1478113129,
  "iat": 1478077129
}
```

<div id="request-user-log-in-with-github">
  ### GitHub を使ってユーザーをログインさせる
</div>

通常のユーザー認証に加え、この例では GitHub などのソーシャル IDプロバイダーにユーザーを直接リダイレクトする方法を示します。この例を動作させるには、[Auth0 Dashboard > Authentication > Social](https://manage.auth0.com/#/connections/social) に移動し、適切な接続を設定する必要があります。接続名は **Settings** タブで確認します。

ユーザーを GitHub のログイン画面に直接リダイレクトするには、ユーザーを認可する際に `connection` パラメーターを渡し、その値を接続名 (この場合は `github`) に設定する必要があります。

export const codeExample15 = `https://{yourDomain}/authorize?
    response_type=code&
    code_challenge={codeChallenge}&
    code_challenge_method=S256&
    client_id={yourClientId}&
    redirect_uri={yourCallbackUrl}&
    scope=openid%20name%20picture&
    state={state}&
    connection=github`;

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

トークンをリクエストすると、IDトークンには GitHub から返されたユーザーの一意の ID を含む `sub` クレームが含まれます。IDトークンをデコードすると、次のような内容になります。

```json lines theme={null}
{
  "name": "John Smith",
  "picture": "https://avatars.example.com",
  "email": "jsmith@...",
  "email_verified": true,
  "iss": "https://auth0user.auth0.com/",
  "sub": "github|100...",
  "aud": "xvt...",
  "exp": 1478114742,
  "iat": 1478078742
}
```

<div id="learn-more">
  ## 詳しく見る
</div>

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