> ## Documentation Index
> Fetch the complete documentation index at: https://docs-dev-ips-6621-xaa-idp-revamp.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

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

> 認可コードフローを使用して、ログインを通常のWebアプリケーションに追加する方法について説明します。

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

認可コードフローを使用すると、ログインを通常のWebアプリケーションに追加することができます。フローの仕組みと使用すべき理由については、[認可コードフロー](/docs/ja-jp/get-started/authentication-and-authorization-flow/authorization-code-flow)をお読みください。通常のWebアプリからAPIを呼び出すには、[認可コードフローを使用してAPIを呼び出す](/docs/ja-jp/get-started/authentication-and-authorization-flow/authorization-code-flow/call-your-api-using-the-authorization-code-flow)をお読みください。

認可コードフローの実装に、Auth0は以下のリソースを提供しています。

* [Regular Web App Quickstarts](/docs/ja-jp/quickstart/webapp)：フローを実装する最も簡単な方法。
* [Authentication API](/docs/ja-jp/api/authentication)：独自のソリューションを構築したい場合は、このまま読み続けて、APIを直接呼び出す方法を学習してください。

ログインに成功すると、アプリケーションがユーザーのIDトークンとアクセストークンにアクセスします。IDトークンには基本的なユーザープロファイル情報が含まれており、アクセストークンはAuth0の`/userinfo`エンドポイントまたは独自の保護されたAPIを呼び出すために使用できます。IDトークンの詳細については、「[IDトークン](/docs/ja-jp/secure/tokens/id-tokens)」をお読みください。アクセストークンの詳細については、「[アクセストークン](/docs/ja-jp/secure/tokens/access-tokens)」をお読みください。

ユーザーの認可を要求し`authorization_code`を使用してアプリにリダイレクトします。そして、トークンのコードを交換します。

## 前提条件

アプリをAuth0に登録する必要があります。詳しくは、[通常のWebアプリケーションを登録する](/docs/ja-jp/get-started/auth0-overview/create-applications/regular-web-apps)をお読みください。

* **［Application Type（アプリケーションタイプ）］**として**［Regular Web App（通常のWebアプリ）］** を選択します。
* `{https://yourApp/callback}`の **［Allowed Callback URL（許可されているコールバックURL）］** を追加します。
* アプリケーションの **［Grant Types（付与タイプ）］** に **［Authorization Code（認可コード）］** が必ず含まれていることを確認してください。詳細については、「[付与タイプを更新する](/docs/ja-jp/get-started/applications/update-grant-types)」をお読みください。

## ユーザーを認可する

フローを開始するには、ユーザーの認可が必要です。この手順には、以下のようなプロセスが含まれます。

* ユーザーを認証する
* 認証を行うために、ユーザーをIDプロバイダーへリダイレクトする
* 以前に同意を得ていない場合は、要求された権限レベルについてユーザーの同意を得る

ユーザーを認可するには、アプリがユーザーを[認可URL](/docs/ja-jp/api/authentication#authorization-code-flow)に送信する必要があります。

### 認可URLの例

export const codeExample1 = `https://{yourDomain}/authorize?
    response_type=code&
    client_id={yourClientId}&
    redirect_uri={https://yourApp/callback}&
    scope={scope}&
    state={state}`;

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

### パラメーター

| パラメーター名         | 説明                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `response_type` | Auth0が返す資格情報の種類を示します（`code`または`token`）。このフローでは、値は`code`でなければなりません。                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `client_id`     | アプリケーションのクライアントID。この値は、[アプリケーション設定](https://manage.auth0.com/#/Applications/\{yourClientId}/settings)で見つけることができます。                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `redirect_uri`  | 認可がユーザーにより付与された後にAuth0がブラウザーをリダイレクトするURL。認可コードは、`code` URLパラメーターで利用できます。[アプリケーション設定](https://manage.auth0.com/#/Applications/\{yourClientId}/settings)で有効なコールバックURLとしてこのURLを指定する必要があります。<br /><br />**警告：** [OAuth 2.0の仕様](https://tools.ietf.org/html/rfc6749#section-3.1.2)に従って、Auth0はハッシュの後、すべてを削除し、フラグメントを受け付け*ません*。                                                                                                                                                                                                                                                                                          |
| `scope`         | 返したいクレーム（またはユーザー属性）を決定する、認可を要求したい[スコープ](/docs/ja-jp/scopes)を指定します。スペースで区切る必要があります。応答でIDトークンを取るには、少なくとも`openid`のスコープを指定する必要があります。ユーザーのフルプロファイルを返したい場合は、`openid 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)を要求できます。`offline_access`を含めてリフレッシュトークンを取得できます（**Allow Offline Access**（オフラインアクセスの許可）フィールドが[アプリケーション設定](https://manage.auth0.com/#/applications)で有効になっていることを確認してください）。 |
| `state`         | （推奨）Auth0がリダイレクトしてアプリケーションに戻る際に含まれ、アプリが初期要求に追加する不透明な任意の英数字の文字列。クロスサイトリクエストフォージェリ（CSRF）攻撃を防止するためにこの値を使用する方法については、[状態パラメーターを使ってCSRF攻撃を軽減する](/docs/ja-jp/protocols/oauth2/mitigate-csrf-attacks)をご覧ください。                                                                                                                                                                                                                                                                                                                                                                                                             |
| `connection`    | （任意）特定の接続でユーザーにサインインを強制します。たとえば、`github`の値を渡して、GitHubアカウントでログインするようにユーザーを直接GitHubに送信します。指定しなかった場合、ユーザーには、構成された接続すべてが表示されたAuth0 Lock画面が表示されます。アプリケーションの**Connections（接続）** タブで構成された接続のリストを確認できます。                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `organization`  | （任意）ユーザーを認証する時に使用する組織のID。提供されない場合、アプリケーションは**Display Organization Prompt（組織のプロンプトを表示）** に設定され、ユーザーは、認証時に組織名を入力できます。                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `invitation`    | （任意）組織の招待のチケットID。\[Organizationにメンバーを招待する]場合(/organizations/invite-members)、ユーザーが招待を受け入れたとき、アプリケーションは、`invitation`および`organization`のキー/値ペアを転送することで、招待の受け入れを処理する必要があります。                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `login_hint`    | （任意）Auth0にリダイレクトされるときに、ログインまたはサインアップページの識別子フィールドに入力します。ユニバーサルログインエクスペリエンスがサポートしています。                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |

たとえば、アプリにログインを追加する際の認可URLのHTMLスニペットは、以下のようになります：

export const codeExample2 = `<a href="https://{yourDomain}/authorize?
  response_type=code&
  client_id={yourClientId}&
  redirect_uri={https://yourApp/callback}&
  scope=openid%20profile&
  state=xyzABC123">
  Sign In
</a>`;

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

### 応答

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

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

## トークンを要求する

取得した認可コードは、トークンと交換する必要があります。前の手順で抽出した認可コード（`code`）を使用して、[トークンURL](/docs/ja-jp/api/authentication#authorization-code)に`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 'client_secret={yourClientSecret}' \
    --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}&client_secret=%7ByourClientSecret%7D&code=yourAuthorizationCode%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}&client_secret=%7ByourClientSecret%7D&code=yourAuthorizationCode%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}&client_secret=%7ByourClientSecret%7D&code=yourAuthorizationCode%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}',
      client_secret: '{yourClientSecret}',
      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:[@"&client_secret={yourClientSecret}" 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}&client_secret=%7ByourClientSecret%7D&code=yourAuthorizationCode%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}&client_secret=%7ByourClientSecret%7D&code=yourAuthorizationCode%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}&client_secret=%7ByourClientSecret%7D&code=yourAuthorizationCode%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("&client_secret={yourClientSecret}".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`          | このチュートリアルの前の手順で取得した`authorization_code`です。                                                                                                                                                                                                |
| `client_id`     | アプリケーションのクライアントIDです。この値は[［Application Settings（アプリケーションの設定）］](https://manage.auth0.com/#/Applications/\{yourClientId}/settings)で見つけることができます。                                                                                              |
| `client_secret` | アプリケーションのクライアントシークレットです。この値は[［Application Settings（アプリケーションの設定）］](https://manage.auth0.com/#/Applications/\{yourClientId}/settings)で見つけることができます。アプリケーションの認証方法については、「[アプリケーションの資格情報](/docs/ja-jp/secure/application-credentials)」をお読みください。 |
| `redirect_uri`  | アプリケーションの設定で指定されている有効なコールバックURLです。このチュートリアルの前の手順で認可URLに渡された`redirect_uri`と完全に一致しなければなりません。これは、URLエンコードする必要があります。                                                                                                                          |

### 応答

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

```javascript lines theme={null}
{
  "access_token": "eyJz93a...k4laUWw",
  "refresh_token": "GEbRxBN...edjnXbL",
  "id_token": "eyJ0XAi...4faeEoQ",
  "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トークン](/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>

## ユースケース

### 基本的な認証要求

この例では、手順1でユーザーを認可する際に行う最も基本的な要求について説明します。Auth0のログイン画面を表示して、構成されている接続でユーザーがサインインできるようにします。

export const codeExample13 = `https://{yourDomain}/authorize?
    response_type=code&
    client_id={yourClientId}&
    redirect_uri={https://yourApp/callback}&
    scope=openid`;

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

トークンを要求する際に、IDトークンには最も基本的なクレームが含まれます。IDトークンをデコードする際には、以下のようになります。

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

### ユーザーの名前とプロファイルの写真を要求する

通常のユーザー認証に加えて、この例では名前や写真など、追加のユーザー詳細情報を要求する方法について説明します。

ユーザーの名前や写真を要求するには、ユーザーを認可する際に、適切なスコープを追加する必要があります。

export const codeExample14 = `https://{yourDomain}/authorize?
    response_type=code&
    client_id={yourClientId}&
    redirect_uri={https://yourApp/callback}&
    scope=openid%20name%20picture&
    state={state}`;

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

トークンを要求する際に、IDトークンには要求された名前と写真のクレームが含まれます。IDトークンをデコードする際には、以下のようになります。

```json lines theme={null}
{
  "name": "jerrie@...",
  "picture": "https://s.gravatar.com/avatar/6222081fd7dcea7dfb193788d138c457?s=480&r=pg&d=https%3A%2F%2Fcdn.auth0.com%2Favatars%2Fje.png",
  "iss": "https://auth0pnp.auth0.com/",
  "sub": "auth0|581...",
  "aud": "xvt...",
  "exp": 1478113129,
  "iat": 1478077129
}
```

### GitHubでのユーザーログインを要求する

通常のユーザー認証に加えて、この例では、ユーザーをGitHubなどのソーシャルIDプロバイダーへ直接送る方法について説明します。まず、[Auth0 Dashboard > Authentication ［Authentication（ 認証）］> Social](https://manage.auth0.com/#/connections/social)で適切な接続を構成し、**［Settings（設定）］** タブから接続名を取得する必要があります。

ユーザーをGitHubログイン画面に直接送信するには、ステップ1でユーザーを認証するときに、`connection`パラメーターを渡し、その値を接続名（この場合は`github`）に設定する必要があります：

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

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

これで、トークンを要求すると、IDトークンにはGitHubから返されたユーザーの一意のIDを含む`sub`クレームが含まれるようになります。IDトークンをデコードする際には、以下のようになります。

```json lines theme={null}
{
  "name": "Jerrie Pelser",
  "nickname": "jerriep",
  "picture": "https://avatars.githubusercontent.com/u/1006420?v=3",
  "iss": "https://auth0pnp.auth0.com/",
  "sub": "github|100...",
  "aud": "xvt...",
  "exp": 1478114742,
  "iat": 1478078742
}
```

## もっと詳しく

* [OAuth 2.0の認可フレームワーク](/docs/ja-jp/authenticate/protocols/oauth)
* [OpenID Connectのプロトコル](/docs/ja-jp/authenticate/protocols/openid-connect-protocol)
* [トークン](/docs/ja-jp/secure/tokens)
* [通常の Webアプリケーションを登録する](/docs/ja-jp/get-started/auth0-overview/create-applications/regular-web-apps)
* [付与タイプの更新](/docs/ja-jp/get-started/applications/update-grant-types)
