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

> OIDC 準拠パイプラインが Authorization Code Flow に与える影響について説明します。

# OIDC に準拠した Authorization Code Flow

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

[Authorization Code Flow](/ja/docs/get-started/authentication-and-authorization-flow/authorization-code-flow) は、シークレットを安全に保存できるサーバーサイドアプリケーションで使用されます。ネイティブアプリケーションでは、[PKCE を使用する認可コードフロー](/ja/docs/get-started/authentication-and-authorization-flow/authorization-code-flow-with-pkce) を使用します。

OIDC 準拠パイプラインは、Authorization Code Flow の次の領域に影響します。

* 認証リクエスト
* 認証レスポンス
* code の交換リクエスト
* code の交換レスポンス
* <Tooltip tip="IDトークン: リソースへのアクセス用ではなく、クライアント自体を対象とした認証情報です。" cta="用語集を表示" href="/ja/docs/glossary?term=ID+token">IDトークン</Tooltip> の構造
* <Tooltip tip="アクセストークン: API へのアクセスに使用される、不透明な文字列または JWT 形式の認可情報です。" cta="用語集を表示" href="/ja/docs/glossary?term=Access+token">アクセストークン</Tooltip> の構造

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

<div id="legacy">
  ### レガシー
</div>

```http lines theme={null}
GET /authorize?
    response_type=code
    &scope=openid email favorite_color offline_access
    &client_id=123
    &state=af0ifjsldkj
    &redirect_uri=https://app.example.com/callback
    &device=my-device-name
```

`offline_access` スコープを指定して <Tooltip tip="リフレッシュトークン: ユーザーに再度ログインさせることなく、新しいアクセストークンを取得するために使用されるトークン。" cta="用語集を見る" href="/ja/docs/glossary?term=refresh+token">リフレッシュトークン</Tooltip> をリクエストする場合にのみ、`device` パラメーターが必要です。詳細については、[Refresh Tokens](/ja/docs/secure/tokens/refresh-tokens) を参照してください。

<div id="oidc-conformant">
  ### OIDC準拠
</div>

```http lines theme={null}
GET /authorize?
    response_type=code
    &scope=openid email offline_access
    &client_id=123
    &state=af0ifjsldkj
    &redirect_uri=https://app.example.com/callback
    &audience=https://api.example.com
```

* `favorite_color` は有効なスコープ値ではなくなりました。
* `device` パラメーターは廃止されました。
* `audience` パラメーターは省略可能です。

<div id="authentication-response">
  ## 認証レスポンス
</div>

Auth0 からのレスポンスは、両方のパイプラインで同一です。

```json lines theme={null}
HTTP/1.1 302 Found
Location: https://app.example.com/callback?
    code=SplxlOBeZQQYbYS6WxSbIA
    &state=af0ifjsldkj
```

<div id="code-exchange-request-authorization-code-flow">
  ## code 交換リクエスト - 認可 code フロー
</div>

認可 code は、どちらのパイプラインでも同じ方法で交換できます。

<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=YOUR_AUTHORIZATION_CODE' \
    --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={yourClientSecret}&code=YOUR_AUTHORIZATION_CODE&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={yourClientSecret}&code=YOUR_AUTHORIZATION_CODE&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<String> 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={yourClientSecret}&code=YOUR_AUTHORIZATION_CODE&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: 'YOUR_AUTHORIZATION_CODE',
      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}&client_secret={yourClientSecret}&code=YOUR_AUTHORIZATION_CODE&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={yourClientSecret}&code=YOUR_AUTHORIZATION_CODE&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={yourClientSecret}&code=YOUR_AUTHORIZATION_CODE&redirect_uri={https://yourApp/callback}"

  response = http.request(request)
  puts response.read_body
  ```
</AuthCodeGroup>

<div id="code-exchange-request-authorization-code-flow-with-pkce">
  ## code の交換リクエスト - PKCE を使用する認可コードフロー
</div>

認可 code は、どちらのパイプラインでも同じ方法で交換できます。

<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=YOUR_GENERATED_CODE_VERIFIER \
    --data code=YOUR_AUTHORIZATION_CODE \
    --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=YOUR_GENERATED_CODE_VERIFIER&code=YOUR_AUTHORIZATION_CODE&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=YOUR_GENERATED_CODE_VERIFIER&code=YOUR_AUTHORIZATION_CODE&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<String> 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=YOUR_GENERATED_CODE_VERIFIER&code=YOUR_AUTHORIZATION_CODE&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: 'YOUR_GENERATED_CODE_VERIFIER',
      code: 'YOUR_AUTHORIZATION_CODE',
      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=YOUR_GENERATED_CODE_VERIFIER&code=YOUR_AUTHORIZATION_CODE&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=YOUR_GENERATED_CODE_VERIFIER&code=YOUR_AUTHORIZATION_CODE&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=YOUR_GENERATED_CODE_VERIFIER&code=YOUR_AUTHORIZATION_CODE&redirect_uri={https://yourApp/callback}"

  response = http.request(request)
  puts response.read_body
  ```
</AuthCodeGroup>

<div id="code-exchange-response">
  ## code の交換レスポンス
</div>

<div id="legacy">
  ### レガシー
</div>

```json lines theme={null}
HTTP/1.1 200 OK
Content-Type: application/json
Cache-Control: no-store
Pragma: no-cache
{
    "access_token": "SlAV32hkKG",
    "token_type": "Bearer",
    "refresh_token": "8xLOxBtZp8",
    "expires_in": 3600,
    "id_token": "eyJ..."
}
```

* 返されるアクセストークンは、[`/userinfo`](https://auth0.com/docs/api/authentication#get-user-info) エンドポイントの呼び出しでのみ有効です。
* リフレッシュトークンが返されるのは、`device` パラメーターが渡され、`offline_access` スコープが要求された場合のみです。

<div id="oidc-conformant">
  ### OIDC準拠
</div>

```json lines theme={null}
HTTP/1.1 200 OK
Content-Type: application/json
Cache-Control: no-store
Pragma: no-cache
{
    "access_token": "eyJ...",
    "token_type": "Bearer",
    "refresh_token": "8xLOxBtZp8",
    "expires_in": 3600,
    "id_token": "eyJ..."
}
```

* 返されるアクセストークンは、`audience` パラメーターで指定した API と [`/userinfo`](https://auth0.com/docs/api/authentication#get-user-info) エンドポイントの呼び出しに使用できます (API が [署名アルゴリズム](/ja/docs/get-started/applications/signing-algorithms) として `RS256` を使用し、`scope` パラメーターに `openid` を使用している場合) 。独自の <Tooltip tip="リソースサーバー: 保護されたリソースをホストするサーバー。リソースサーバーは、保護されたリソースへのリクエストを受け入れて応答します。" cta="用語集を見る" href="/ja/docs/glossary?term=Resource+Server">Resource Server</Tooltip> (API) を実装していない場合は、`audience` パラメーターとして `https://{$account.namespace}/userinfo` を使用できます。この場合、不透明なアクセストークンが返されます。
* リフレッシュトークンが返されるのは、`offline_access` スコープが付与されている場合のみです。

<div id="id-token-structure">
  ## IDトークンの構造
</div>

<div id="legacy">
  ### レガシー
</div>

export const codeExample21 = `{
    "sub": "auth0|alice",
    "iss": "https://{yourDomain}/",
    "aud": "123",
    "exp": 1482809609,
    "iat": 1482773609,
    "email": "alice@example.com",
    "email_verified": true,
    "favorite_color": "blue"
}`;

<AuthCodeBlock children={codeExample21} language="json" filename="JSON" />

<div id="oidc-conformant">
  ### OIDC準拠
</div>

export const codeExample22 = `{
    "sub": "auth0|alice",
    "iss": "https://{yourDomain}/",
    "aud": "123",
    "exp": 1482809609,
    "iat": 1482773609,
    "email": "alice@example.com",
    "email_verified": true,
    "https://app.example.com/favorite_color": "blue"
}`;

<AuthCodeBlock children={codeExample22} language="json" filename="JSON" />

`favorite_color` クレームは、Auth0 Action を使用して追加する必要があります。詳細については、[カスタムクレームの作成](/ja/docs/secure/tokens/json-web-tokens/create-custom-claims)を参照してください。

<div id="access-token-structure-optional">
  ## アクセストークンの構造 (任意)
</div>

<div id="legacy">
  ### レガシー
</div>

```bash HTTP lines theme={null}
SlAV32hkKG
```

返されたアクセストークンは不透明であり、[`/userinfo`](https://auth0.com/docs/api/authentication#get-user-info) エンドポイントの呼び出しにのみ使用できます。

<div id="oidc-conformant">
  ### OIDC準拠
</div>

export const codeExample23 = `{
    "sub": "auth0|alice",
    "iss": "https://{yourDomain}/",
    "aud": [
        "https://api.example.com",
        "https://{yourDomain}/userinfo"
    ],
    "azp": "123",
    "exp": 1482816809,
    "iat": 1482809609,
    "scope": "openid email"
}`;

<AuthCodeBlock children={codeExample23} language="json" filename="JSON" />

返されたアクセストークンは、必要に応じて、`audience` パラメーターで指定した API と [`/userinfo`](https://auth0.com/docs/api/authentication#get-user-info) エンドポイントの呼び出しに使用できます (API が <Tooltip tip="署名アルゴリズム: トークンが改ざんされていないことを保証するために、トークンにデジタル署名する際に使用されるアルゴリズムです。" cta="用語集を見る" href="/ja/docs/glossary?term=signing+algorithm">署名アルゴリズム</Tooltip> として `RS256` を使用し、`scope` パラメーターに `openid` が指定されている場合) 。

独自のリソースサーバー (API) を実装しない場合は、`audience` パラメーターに `https://{$account.namespace}/userinfo` を使用できます。この場合は、不透明なアクセストークンが返されます。

<div id="learn-more">
  ## 詳細
</div>

* [OIDC でのアクセストークン](/ja/docs/authenticate/login/oidc-conformant-authentication/oidc-adoption-access-tokens)
* [OIDC での外部 API](/ja/docs/authenticate/login/oidc-conformant-authentication/oidc-adoption-apis)
* [OIDC でのクライアントクレデンシャルフロー](/ja/docs/authenticate/login/oidc-conformant-authentication/oidc-adoption-client-credentials-flow)
* [OIDC でのインプリシットフロー](/ja/docs/authenticate/login/oidc-conformant-authentication/oidc-adoption-implicit-flow)
* [OIDC でのリフレッシュトークン](/ja/docs/authenticate/login/oidc-conformant-authentication/oidc-adoption-refresh-tokens)
* [OIDC でのリソースオーナーパスワードフロー](/ja/docs/authenticate/login/oidc-conformant-authentication/oidc-adoption-rop-flow)
