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

> Auth0 Custom Social Connections を使用して、任意の OAuth2 プロバイダーを追加する方法を説明します。

# アプリを汎用 OAuth2 認可サーバーに接続する

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

最も一般的な[IDプロバイダー (IdP) ](/ja/docs/authenticate/identity-providers)は、[Auth0 Dashboard](https://manage.auth0.com/#)と[Auth0 Marketplace](https://marketplace.auth0.com/features/social-connections)で利用できます。ただし、任意の<Tooltip tip="OAuth 2.0: 認可プロトコルとワークフローを定義する認可フレームワーク。" cta="用語集を表示" href="/ja/docs/glossary?term=OAuth+2.0">OAuth 2.0</Tooltip>プロバイダーを、<Tooltip tip="Auth0 Dashboard: サービスを設定するための Auth0 の主要製品。" cta="用語集を表示" href="/ja/docs/glossary?term=Auth0+Dashboard">Auth0 Dashboard</Tooltip>で**Custom Social Connection**として追加することもできます。

1. Dashboard で、[Authentication > Social](https://manage.auth0.com/#/connections/social)に移動します。
2. **Create Connection**を選択し、リストの一番下まで移動してから**Create Custom**を選択します。

表示されるフォームには、カスタム接続を設定するために必要な複数のフィールドがあります。

* **Connection Name**: 作成する接続の論理識別子です。この名前は変更できず、先頭と末尾は英数字である必要があり、使用できるのは英数字とダッシュのみです。
* **Authorization URL**: ユーザーがログインのためにリダイレクトされる URL です。

  <Callout icon="file-lines" color="#0EA5E9" iconType="regular">
    認可 URL で OAuth 2.0 の `response_mode` パラメーターを設定しないでください。この接続でサポートされる `response_mode` はデフォルトの `query` のみです。
  </Callout>
* **Token URL**: 受け取った認可コードを<Tooltip tip="アクセストークン: API へのアクセスに使用される、不透明な文字列または JWT 形式の認可資格情報。" cta="用語集を表示" href="/ja/docs/glossary?term=access+tokens">アクセストークン</Tooltip>および、要求された場合は<Tooltip tip="IDトークン: リソースへのアクセスではなく、クライアント自体を対象とした資格情報。" cta="用語集を表示" href="/ja/docs/glossary?term=ID+tokens">IDトークン</Tooltip>と交換するための URL です。
* **Scope**: 認可リクエストとともに送信する `scope` パラメーターです。複数のスコープはスペースで区切ります。
* **Separate scopes using a space**: [IdP の API を呼び出す](/ja/docs/authenticate/identity-providers/calling-an-external-idp-api)際に `connection_scope` パラメーターが含まれている場合、スコープの区切り方法を決定するトグルです。デフォルトでは、スコープはコンマで区切られます。トグルを有効にすると、スコープはスペースで区切られます。詳細は、[IDプロバイダー API を呼び出すためのスコープ/Permissions の追加](/ja/docs/authenticate/identity-providers/adding-scopes-for-an-external-idp)を参照してください。
* **<Tooltip tip="クライアントID: 登録済みリソースに Auth0 から付与される識別値。" cta="用語集を表示" href="/ja/docs/glossary?term=Client+ID">Client ID</Tooltip>**: 認可を要求し、認可コードを交換するためにアプリケーションとして使用される Auth0 のクライアントIDです。Client ID を取得するには、<Tooltip tip="IDプロバイダー（IdP）: デジタル ID を保存および管理するサービス。" cta="用語集を表示" href="/ja/docs/glossary?term=identity+provider">IDプロバイダー</Tooltip>に登録する必要があります。
* **<Tooltip tip="クライアントシークレット: クライアント（アプリケーション）が認可サーバーに対して認証するために使用する秘密情報です。クライアントと認可サーバーのみが知るべきものであり、推測されないよう十分にランダムである必要があります。" cta="用語集を表示" href="/ja/docs/glossary?term=Client+Secret">Client Secret</Tooltip>**: 認可コードの交換に使用される、アプリケーションとしての Auth0 のクライアントシークレットです。Client Secret を取得するには、IDプロバイダーに登録する必要があります。
* **ユーザープロファイル取得スクリプト**: 提供されたアクセストークンを使用して userinfo URL を呼び出すための Node.js スクリプトです。詳細は、[ユーザープロファイル取得スクリプト](#fetch-user-profile-script)を参照してください。
* **Purpose**: 認証、Token Vault の Connected Accounts、またはその両方でソーシャル接続を有効にします。詳細は、[ユーザー認証と Connected Accounts](/ja/docs/secure/tokens/token-vault/connected-accounts-for-token-vault#user-authentication-vs-connected-accounts)を参照してください。

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  カスタムIDプロバイダーを設定する際は、コールバックURL `https://{yourDomain}/login/callback` を使用してください。
</Callout>

カスタム接続を作成すると、**Applications** ビューが表示され、その接続には Auth0 の[レート制限ポリシー](/ja/docs/troubleshoot/customer-support/operational-policies/rate-limit-policy)が適用されます。ここでは、この接続を表示するアプリケーションを有効または無効にできます。

<div id="update-authentication-flow">
  ## 認証フローを更新する
</div>

接続を作成すると、その接続に割り当てられるデフォルトの OAuth 2.0 グラントタイプは Authorization Code Flow です。シングルページアプリケーションやネイティブアプリケーションなど、クライアントシークレットを保存できないパブリックアプリケーションの場合は、<Tooltip tip="Management API: 顧客が管理タスクを実行できるようにする製品です。" cta="用語集を表示" href="/ja/docs/glossary?term=Management+API">Management API</Tooltip> を使用して、接続が [Authorization Code Flow + PKCE](/ja/docs/get-started/authentication-and-authorization-flow/authorization-code-flow-with-pkce) を使用するよう更新できます。<Tooltip tip="Authorization Flow: OAuth 2.0 フレームワークで指定される認可グラント（またはワークフロー）です。" cta="用語集を表示" href="/ja/docs/glossary?term=authorization+flows">認可フロー</Tooltip> の詳細については、[どの OAuth 2.0 フローを使用すべきですか？](/ja/docs/get-started/authentication-and-authorization-flow/which-oauth-2-0-flow-should-i-use) を参照してください

1. [`/get-connections-by-id`](https://auth0.com/docs/api/management/v2/connections/get-connections-by-id) エンドポイントに `GET` リクエストを送信します。レスポンスは次のようになります。

   ```json lines theme={null}
   {
     "id": "[connectionID]",
     "options": {
       "email": true,
       "scope": [
         "email",
         "profile"
       ],
       "profile": true
     },
     "strategy": "google-oauth2",
     "name": "google-oauth2",
     "is_domain_connection": false,
     "realms": [
       "google-oauth2"
     ]
   }
   ```

2. `options` オブジェクト全体をコピーします。

3. `options` オブジェクトを含めた [`PATCH`](https://auth0.com/docs/api/management/v2/connections/patch-connections-by-id) リクエストを送信し、`"pkce_enabled":` `true` を追加します。

<Warning>
  `options` オブジェクト全体を含めないと、情報が失われ、接続が機能しなくなります。
</Warning>

<div id="fetch-user-profile-script">
  ## ユーザープロファイル取得スクリプト
</div>

ユーザープロファイル取得スクリプトは、ユーザーが OAuth2 プロバイダーを使用してログインした後に呼び出されます。Auth0 はこのスクリプトを実行して OAuth2 プロバイダーの API を呼び出し、ユーザープロファイルを取得します。

```javascript lines expandable theme={null}
function fetchUserProfile(accessToken, context, callback) {
  request.get(
    {
      url: 'https://auth.example.com/userinfo',
      headers: {
        'Authorization': 'Bearer ' + accessToken,
      }
    },
    (err, resp, body) => {
      if (err) {
        return callback(err);
      }
      if (resp.statusCode !== 200) {
        return callback(new Error(body));
      }
      let bodyParsed;
      try {
        bodyParsed = JSON.parse(body);
      } catch (jsonError) {
        return callback(new Error(body));
      }
      const profile = {
        user_id: bodyParsed.account.uuid,
        email: bodyParsed.account.email
      };
      callback(null, profile);
    }
  );
}
```

返されるユーザープロファイルでは、`user_id` プロパティは必須です。`email` プロパティは任意ですが、含めることを強く推奨します。返される属性の詳細については、[User Profile Root Attributes](/ja/docs/manage-users/user-accounts/user-profiles/root-attributes/update-root-attributes-for-users)を参照してください。

プロバイダーから返されるユーザープロファイルでは、任意の項目をフィルタリングしたり、追加したり、削除したりできます。ただし、このスクリプトはできるだけシンプルに保つことをお勧めします。ユーザー情報をより高度に操作するには、[Rules](/ja/docs/customize/rules)を使用できます。Rules を使用する利点の 1 つは、どの接続にも適用されることです。

<div id="log-in-using-the-custom-connection">
  ## カスタム接続を使用してログインする
</div>

Auth0 の標準的なメカニズムはどれでも、カスタム接続を使ったユーザーのログインに利用できます。直接リンクの例は次のとおりです。

export const codeExample1 = `https://{yourDomain}/authorize
  ?response_type=code
  &client_id={yourClientId}
  &redirect_uri={https://yourApp/callback}
  &scope=openid%20profile%20email
  &connection=NAME_OF_CONNECTION`;

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

<div id="modify-the-icon-and-display-name">
  ## アイコンと表示名を変更する
</div>

IDプロバイダーのログインボタンにアイコンを追加したり、ログインボタンに表示されるテキストを変更したりするには、[Management API](https://auth0.com/docs/api/management/v2#!/Connections/patch_connections_by_id) を使用して、それぞれ `options` オブジェクトの `icon_url` プロパティと `display_name` プロパティを設定します。

<Warning>
  * リクエストに `display_name` が含まれていない場合、このフィールドは接続の `name` 値で上書きされます。
  * `display_name` と `icon_url` は、[Universal Login experience](/ja/docs/authenticate/login/auth0-universal-login/universal-login-vs-classic-login/universal-experience) での接続の表示方法にのみ影響します。
</Warning>

<AuthCodeGroup>
  ```bash cURL theme={null}
  curl --request PATCH \
    --url 'https://{yourDomain}/api/v2/connections/CONNECTION-ID' \
    --header 'content-type: application/json' \
    --data '{ "options": { "client_id": "...", "client_secret": "...", "icon_url": "https://cdn.example.com/assets/icon.png", "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://public-auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "display_name": "Connection Name"}'
  ```

  ```csharp C# theme={null}
  var client = new RestClient("https://{yourDomain}/api/v2/connections/CONNECTION-ID");
  var request = new RestRequest(Method.PATCH);
  request.AddHeader("content-type", "application/json");
  request.AddParameter("application/json", "{ "options": { "client_id": "...", "client_secret": "...", "icon_url": "https://cdn.example.com/assets/icon.png", "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://public-auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" , "display_name": "Connection Name" }, ParameterType.RequestBody);
  ```

  ```go Go theme={null}
  package main

  import (
  	"fmt"
  	"strings"
  	"net/http"
  	"io/ioutil"
  )

  func main() {

  	url := "https://{yourDomain}/api/v2/connections/CONNECTION-ID"

  	payload := strings.NewReader("{ "options": { "client_id": "...", "client_secret": "...", "icon_url": "https://cdn.example.com/assets/icon.png", "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://public-auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "display_name": "Connection Name"}")

  	req, _ := http.NewRequest("PATCH", url, payload)

  	req.Header.Add("content-type", "application/json")

  	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.patch("https://{yourDomain}/api/v2/connections/CONNECTION-ID")
    .header("content-type", "application/json")
    .body("{ "options": { "client_id": "...", "client_secret": "...", "icon_url": "https://cdn.example.com/assets/icon.png", "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://public-auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "display_name": "Connection Name"})
    .asString();
  ```

  ```javascript Node.JS theme={null}
  var axios = require("axios").default;

  var options = {
    method: 'PATCH',
    url: 'https://{yourDomain}/api/v2/connections/CONNECTION-ID',
    headers: {'content-type': 'application/json'},
    data: '{ "options": { "client_id": "...", "client_secret": "...", "icon_url": "https://cdn.example.com/assets/icon.png", "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://public-auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "display_name": "Connection Name"}'

  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}/api/v2/connections/CONNECTION-ID",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "PATCH",
    CURLOPT_POSTFIELDS => "{ "options": { "client_id": "...", "client_secret": "...", "icon_url": "https://cdn.example.com/assets/icon.png", "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://public-auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "display_name": "Connection Name"}",
    CURLOPT_HTTPHEADER => [
      "content-type: application/json"
    ],
  ]);

  $response = curl_exec($curl);
  $err = curl_error($curl);

  curl_close($curl);

  if ($err) {
    echo "cURL Error #:" . $err;
  } else {
    echo $response;
  }
  ```

  ```python Python theme={null}
  import http.client

  conn = http.client.HTTPSConnection("")

  payload = "{ "options": { "client_id": "...", "client_secret": "...", "icon_url": "https://cdn.example.com/assets/icon.png", "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://public-auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "display_name": "Connection Name"}"

  headers = { 'content-type': "application/json" }

  conn.request("PATCH", "/{yourDomain}/api/v2/connections/CONNECTION-ID", 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}/api/v2/connections/CONNECTION-ID")

  http = Net::HTTP.new(url.host, url.port)
  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL::VERIFY_NONE

  request = Net::HTTP::Patch.new(url)
  request["content-type"] = 'application/json'
  request.body = "{ "options": { "client_id": "...", "client_secret": "...", "icon_url": "https://cdn.example.com/assets/icon.png", "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://public-auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "display_name": "Connection Name"}"

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

<div id="pass-provider-specific-parameters">
  ## プロバイダー固有のパラメーターを渡す
</div>

OAuth 2.0 プロバイダーの認可エンドポイントに、プロバイダー固有のパラメーターを渡すことができます。これらのパラメーターは、静的または動的に指定できます。

<div id="pass-static-parameters">
  ### 静的パラメーターを渡す
</div>

静的パラメーター (すべての認可リクエストで送信されるパラメーター) を渡すには、[Management API](https://auth0.com/docs/api/management/v2#!/Connections/patch_connections_by_id) 経由で OAuth 2.0 の接続を設定する際に、`options` の `authParams` 要素を使用できます。以下の呼び出しでは、すべての認可リクエストに対して、`custom_param` という静的パラメーターが `custom.param.value` に設定されます。

<AuthCodeGroup>
  ```bash cURL theme={null}
  curl --request PATCH \
    --url 'https://{yourDomain}/api/v2/connections/CONNECTION-ID' \
    --header 'content-type: application/json' \
    --data '{ "options": { "client_id": "...", "client_secret": "...", "authParams": { "custom_param": "custom.param.value" }, "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://public-auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" } }'
  ```

  ```csharp C# theme={null}
  var client = new RestClient("https://{yourDomain}/api/v2/connections/CONNECTION-ID");
  var request = new RestRequest(Method.PATCH);
  request.AddHeader("content-type", "application/json");
  request.AddParameter("application/json", "{ "options": { "client_id": "...", "client_secret": "...", "authParams": { "custom_param": "custom.param.value" }, "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://public-auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" } }", 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}/api/v2/connections/CONNECTION-ID"

  	payload := strings.NewReader("{ "options": { "client_id": "...", "client_secret": "...", "authParams": { "custom_param": "custom.param.value" }, "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://public-auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" } }")

  	req, _ := http.NewRequest("PATCH", url, payload)

  	req.Header.Add("content-type", "application/json")

  	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.patch("https://{yourDomain}/api/v2/connections/CONNECTION-ID")
    .header("content-type", "application/json")
    .body("{ "options": { "client_id": "...", "client_secret": "...", "authParams": { "custom_param": "custom.param.value" }, "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://public-auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" } }")
    .asString();
  ```

  ```javascript Node.JS theme={null}
  var axios = require("axios").default;

  var options = {
    method: 'PATCH',
    url: 'https://{yourDomain}/api/v2/connections/CONNECTION-ID',
    headers: {'content-type': 'application/json'},
    data: {
      options: {
        client_id: '...',
        client_secret: '...',
        authParams: {custom_param: 'custom.param.value'},
        scripts: {fetchUserProfile: '...'},
        authorizationURL: 'https://public-auth.example.com/oauth2/authorize',
        tokenURL: 'https://auth.example.com/oauth2/token',
        scope: 'auth'
      },
    },
  };

  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}/api/v2/connections/CONNECTION-ID",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "PATCH",
    CURLOPT_POSTFIELDS => "{ "options": { "client_id": "...", "client_secret": "...", "authParams": { "custom_param": "custom.param.value" }, "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://public-auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" } }"
    CURLOPT_HTTPHEADER => [
      "content-type: application/json"
    ],
  ]);

  $response = curl_exec($curl);
  $err = curl_error($curl);

  curl_close($curl);

  if ($err) {
    echo "cURL Error #:" . $err;
  } else {
    echo $response;
  }
  ```

  ```python Python theme={null}
  import http.client

  conn = http.client.HTTPSConnection("")

  payload = "{ "options": { "client_id": "...", "client_secret": "...", "authParams": { "custom_param": "custom.param.value" }, "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://public-auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" } }"

  headers = { 'content-type': "application/json" }

  conn.request("PATCH", "/{yourDomain}/api/v2/connections/CONNECTION-ID", 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}/api/v2/connections/CONNECTION-ID")

  http = Net::HTTP.new(url.host, url.port)
  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL::VERIFY_NONE

  request = Net::HTTP::Patch.new(url)
  request["content-type"] = 'application/json'
  request.body = "{ "options": { "client_id": "...", "client_secret": "...", "authParams": { "custom_param": "custom.param.value" }, "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://public-auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }}"

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

<div id="pass-dynamic-parameters">
  ### 動的パラメーターを渡す
</div>

状況によっては、OAuth 2.0 のIDプロバイダーに動的な値を渡したいことがあります。この場合は、`options` の `authParamsMap` 要素を使用して、[Auth0 の `/authorize` エンドポイント](https://auth0.com/docs/api/authentication#social) で受け付けられる既存の追加パラメーターの 1 つと、IDプロバイダーで受け付けられるパラメーターとのマッピングを指定できます。

前述の例をそのまま使うと、認可エンドポイントに `custom_param` パラメーターを渡したい一方で、実際のパラメーター値は Auth0 の `/authorize` エンドポイントを呼び出す際に指定したいとします。

この場合は、`/authorize` エンドポイントで受け付けられる既存の追加パラメーター (`access_type` など) を 1 つ使用し、それを `custom_param` パラメーターにマッピングできます。

<AuthCodeGroup>
  ```bash cURL theme={null}
  curl --request PATCH \
    --url 'https://{yourDomain}/api/v2/connections/CONNECTION-ID' \
    --header 'content-type: application/json' \
    --data '{ "options": { "client_id": "...", "client_secret": "...", "authParamsMap": { "custom_param": "access_type" }, "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" } }'
  ```

  ```csharp C# theme={null}
  var client = new RestClient("https://{yourDomain}/api/v2/connections/CONNECTION-ID");
  var request = new RestRequest(Method.PATCH);
  request.AddHeader("content-type", "application/json");
  request.AddParameter("application/json", "{ "options": { "client_id": "...", "client_secret": "...", "authParamsMap": { "custom_param": "access_type" }, "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" } }", 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}/api/v2/connections/CONNECTION-ID"

  	payload := strings.NewReader("{ "options": { "client_id": "...", "client_secret": "...", "authParamsMap": { "custom_param": "access_type" }, "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }
    }")

  	req, _ := http.NewRequest("PATCH", url, payload)

  	req.Header.Add("content-type", "application/json")

  	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.patch("https://{yourDomain}/api/v2/connections/CONNECTION-ID")
    .header("content-type", "application/json")
    .body("{ "options": { "client_id": "...", "client_secret": "...", "authParamsMap": { "custom_param": "access_type" }, "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" } }")
    .asString();
  ```

  ```javascript Node.JS theme={null}
  var axios = require("axios").default;

  var options = {
    method: 'PATCH',
    url: 'https://{yourDomain}/api/v2/connections/CONNECTION-ID',
    headers: {'content-type': 'application/json'},
    data: {
      options: {
        client_id: '...',
        client_secret: '...',
        authParamsMap: {custom_param: 'access_type'},
        scripts: {fetchUserProfile: '...'},
        authorizationURL: 'https://auth.example.com/oauth2/authorize',
        tokenURL: 'https://auth.example.com/oauth2/token',
        scope: 'auth'
      },
    }
  };

  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}/api/v2/connections/CONNECTION-ID",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "PATCH",
    CURLOPT_POSTFIELDS => "{ "options": { "client_id": "...", "client_secret": "...", "authParamsMap": { "custom_param": "access_type" }, "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" } }"
    CURLOPT_HTTPHEADER => [
      "content-type: application/json"
    ],
  ]);

  $response = curl_exec($curl);
  $err = curl_error($curl);

  curl_close($curl);

  if ($err) {
    echo "cURL Error #:" . $err;
  } else {
    echo $response;
  }
  ```

  ```python Python theme={null}
  import http.client

  conn = http.client.HTTPSConnection("")

  payload = "{ "options": { "client_id": "...", "client_secret": "...", "authParamsMap": { "custom_param": "access_type" }, "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" } 
  }"

  headers = { 'content-type': "application/json" }

  conn.request("PATCH", "/{yourDomain}/api/v2/connections/CONNECTION-ID", 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}/api/v2/connections/CONNECTION-ID")

  http = Net::HTTP.new(url.host, url.port)
  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL::VERIFY_NONE

  request = Net::HTTP::Patch.new(url)
  request["content-type"] = 'application/json'
  request.body = "{ "options": { "client_id": "...", "client_secret": "...", "authParamsMap": { "custom_param": "access_type" }, "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }
  }"

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

これで、`/authorize` エンドポイントの呼び出し時に、`access_type` パラメーターでアクセス種別を渡せるようになり、その値は `custom_param` パラメーターを介して認可エンドポイントに渡されます。

<div id="pass-extra-headers">
  ## 追加ヘッダーを渡す
</div>

状況によっては、OAuth 2.0 プロバイダーの<Tooltip tip="Token Endpoint: トークンをプログラムでリクエストするために使用される、認可サーバー上のエンドポイント。" cta="用語集を表示" href="/ja/docs/glossary?term=Token+endpoint">トークンエンドポイント</Tooltip>に追加ヘッダーを渡す必要があります。追加ヘッダーを設定するには、接続の設定を開き、**Custom Headers** フィールドで、カスタムヘッダーをキーと値のペアとして含む JSON オブジェクトを指定します。

```json lines theme={null}
{
    "Header1" : "Value",
    "Header2" : "Value"
}
```

IDプロバイダーから、[Basic 認証](https://en.wikipedia.org/wiki/Basic_access_authentication) の認証情報を含む `Authorization` ヘッダーを渡すよう求められるケースを例に見てみましょう。このシナリオでは、**Custom Headers** フィールドに次の JSON オブジェクトを指定できます。

```json lines theme={null}
{
  "Authorization": "Basic [your credentials]"
}
```

ここで、`[your credentials]` は IDプロバイダーに実際に送信する認証情報です。

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

* [ソーシャルIDプロバイダー](/ja/docs/authenticate/identity-providers/social-identity-providers)
* [IDプロバイダー](/ja/docs/authenticate/identity-providers)
* [プロトコル](/ja/docs/authenticate/protocols)
