> ## 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 を使用した Authorization Code フローを使って、Native、モバイル、またはシングルページ アプリケーションにログインを追加する方法を学びます。

# PKCE を使用した Authorization Code フローでログインを追加する

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

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

Proof Key for Code Exchange (PKCE) を使用した Authorization Code フローを実装するには、次のリソースを利用できます。

* [Auth0 Mobile SDKs](/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) では、手順を順を追って説明しています。
* [Authentication API](https://auth0.com/docs/api/authentication): 独自のソリューションを構築したい場合は、このまま読み進めて、API を直接呼び出す方法をご確認ください。

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

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

Auth0 にアプリケーションを登録します。詳しくは、[ネイティブアプリケーションを登録する](/docs/ja-jp/get-started/auth0-overview/create-applications/native-apps) または [シングルページ Web アプリケーションを登録する](/docs/ja-jp/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 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) をご覧ください。

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

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

`code_verifier` を作成するアルゴリズムの詳細については、<Tooltip tip="OAuth 2.0: 認可プロトコルとワークフローを定義する認可フレームワーク。" cta="用語集を見る" href="/docs/ja-jp/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);
```

### Swift 5 の例

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

### Objective-C の例

```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">
  ## コードチャレンジを作成する
</div>

Auth0 に送信して `authorization_code` をリクエストするための `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.) を参照してください。

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

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

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

```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 フレームワークで指定された Authorization グラント（またはワークフロー）。" cta="用語集を見る" href="/docs/ja-jp/glossary?term=authorization+flow">認可フロー</Tooltip> の始まりであり、このステップには次のプロセスのうち1つ以上が含まれる場合があります。

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

ユーザーを認可するには、アプリでユーザーを [authorization 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>

| パラメータ名                  | 説明                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `response_type`         | Auth0 が返す認証情報の種類 (`code` または `token`) を示します。このフローでは、値は `code` である必要があります。                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `code_challenge`        | `code_verifier` から生成されたチャレンジです。                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `code_challenge_method` | チャレンジの生成に使用するメソッド (例: `S256`) です。PKCE 仕様では `S256` と `plain` の 2 つのメソッドが定義されています。この例では前者を使用しており、後者は非推奨であるため、Auth0 でサポートされているのは **前者のみ** です。                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `client_id`             | アプリケーションの Client ID です。この値は [アプリケーション設定](https://manage.auth0.com/#/Applications/\{yourClientId}/settings) で確認できます。                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| `redirect_uri`          | ユーザーが認可した後、Auth0 がブラウザーをリダイレクトする先の URL です。認可コードは URL パラメータ `code` で受け取れます。この URL は、[アプリケーション設定](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`                 | 認可をリクエストする対象の [scopes](/docs/ja-jp/get-started/apis/scopes) を指定します。これにより、返されるクレーム (またはユーザー属性) が決まります。複数指定する場合はスペースで区切る必要があります。レスポンスで ID トークンを取得するには、少なくとも `openid` スコープを指定する必要があります。ユーザーの完全なプロファイルを返したい場合は、`openid profile` をリクエストできます。`email` など、ユーザーに関する [standard OpenID Connect (OIDC) scopes](https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims) や、[namespaced format](/docs/ja-jp/secure/tokens/json-web-tokens/create-custom-claims) に準拠した [custom claims](/docs/ja-jp/secure/tokens/json-web-tokens/json-web-token-claims#custom-claims) をリクエストすることもできます。[リフレッシュトークン](/docs/ja-jp/glossary?term=Refresh+Token) を取得するには `offline_access` を含めます ([アプリケーション設定](https://manage.auth0.com/#/applications) で **オフラインアクセスの許可** フィールドが有効になっていることを確認してください) 。 |
| `state`                 | (推奨) アプリが最初の request に追加する、任意の英数字からなる不透明な文字列です。Auth0 はアプリケーションにリダイレクトするとき、この値をそのまま含めます。この値を使ってクロスサイトリクエストフォージェリ (CSRF) 攻撃を防ぐ方法については、[Mitigate CSRF Attacks With State Parameters](/docs/ja-jp/secure/attack-protection/state-parameters) を参照してください。                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| `connection`            | (任意) ユーザーが特定の接続でサインインするようにします。たとえば、`github` を渡すと、ユーザーは GitHub アカウントでログインするために直接 GitHub に移動します。指定しない場合、ユーザーには設定済みのすべての接続を含む Auth0 Lock 画面が表示されます。設定済みの接続の一覧は、アプリケーションの **Connections** タブで確認できます。                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `organization`          | (任意) ユーザー認証時に使用する organization の ID です。指定しない場合でも、アプリケーションで **Display Organization Prompt** が設定されていれば、ユーザーは認証時に organization名 を入力できます。                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `invitation`            | (任意) organization 招待の ticket ID です。[Organizations にメンバーを招待する](/docs/ja-jp/manage-users/organizations/configure-organizations/invite-members) 場合は、ユーザーが招待を承諾した際に、アプリケーションで `invitation` と `organization` のキーと値のペアを転送して、招待承諾を処理する必要があります。                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |

例として、アプリに login を追加する際の認可 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` を付けて [Token URL](https://auth0.com/docs/api/authentication#authorization-code-pkce-) に `POST` リクエストを送信します。

<div id="post-to-token-url-example">
  ### Token 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_PEER

  request = Net::HTTP::Post.new(url)
  request["content-type"] = 'application/x-www-form-urlencoded'
  request.body = "grant_type=authorization_code&client_id={yourClientId}&code_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`     | アプリケーションの Client ID です。この値は [アプリケーション設定](https://manage.auth0.com/#/Applications/\{yourClientId}/settings) で確認できます。 |
| `redirect_uri`  | アプリケーション設定で設定した有効なコールバック 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 Token を検証する](/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 Authentication API の /userinfo エンドポイント](https://auth0.com/docs/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 トークンの有効期限が切れたあとに、新しいアクセストークンまたは ID トークンを取得するために使用されます。`refresh_token`がレスポンスに含まれるのは、`offline_access` scope を含め、Auth0 Dashboard で API の**オフラインアクセスの許可**を有効にしている場合のみです。

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

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

<div id="basic-authentication-request">
  ### 基本的な認証リクエスト
</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 トークンにはリクエストした名前とプロフィール画像のクレームが含まれるようになります。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 などのソーシャルアイデンティティプロバイダーへユーザーを直接送る方法を示します。この例を機能させるには、[Auth0 Dashboard > Authentication > Social](https://manage.auth0.com/#/connections/social) に移動して、適切な接続を設定する必要があります。接続名は **設定** タブで確認してください。

ユーザーを 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 認可フレームワーク](/docs/ja-jp/authenticate/protocols/oauth)
* [OpenID Connect プロトコル](/docs/ja-jp/authenticate/protocols/openid-connect-protocol)
* [トークン](/docs/ja-jp/secure/tokens)
