> ## Documentation Index
> Fetch the complete documentation index at: https://auth0.com/llms.txt
> Use this file to discover all available pages before exploring further.

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

> Auth0のカスタムソーシャル接続を使用して、任意の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) + "*****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>;
};

最も一般的な[IDプロバイダー（IdP）](/docs/ja-jp/authenticate/identity-providers)は、[Auth0 Dashboard](https://manage.auth0.com/#)や[Auth0 Marketplace](https://marketplace.auth0.com/features/social-connections)から利用できます。ただし、<Tooltip data-tooltip-id="react-containers-DefinitionTooltip-0" href="/docs/ja-jp/glossary?term=auth0-dashboard" tip="Auth0 Dashboard: サービスを構成するためのAuth0の主製品。" cta="用語集の表示">Auth0 Dashboard</Tooltip>では、任意の<Tooltip data-tooltip-id="react-containers-DefinitionTooltip-1" href="/docs/ja-jp/glossary?term=oath2" tip="OAuth 2.0: 認可プロトコルとワークフローを定義する認可フレームワーク。" cta="用語集の表示">OAuth 2.0</Tooltip>プロバイダーを **カスタムソーシャル接続** として追加することもできます。

1. Dashboardから、[［Authentication（認証）］>［Social（ソーシャル）］](https://manage.auth0.com/#/connections/social)に移動します。
2. **［Create Connection（接続を作成）］** を選択し、リストの下部に移動してから **［Create Custom（カスタムを作成）］** を選択します。

表示されるフォームには、カスタム接続の構成に使用しなければならないフィールドがいくつかあります。

* **Connection Name（接続名）** ：作成している接続の論理識別子です。この名前は変更できません。先頭と末尾が英数字でなければなりません。英数字とダッシュ以外は使用できません。

* **Authorization URL（認可URL）** ：URLユーザーがログインのためにリダイレクトされるURLです。

  <Callout icon="file-lines" color="#0EA5E9" iconType="regular">
    認可URLにあるOAuth2の`response_mode`パラメーターは設定しないでください。この接続は、デフォルトの`response_mode`（`query`）のみに対応しています。
  </Callout>

* **Token URL（トークンURL）** ：URL受け取った認可コードをアクセストークンとIDトークン（要求された場合）に交換するために使用されます。

* **Scope（スコープ）** ：認可要求と一緒に送信する`scope`パラメーターです。複数のスコープはスペースで区切ります。

* **Separate scopes using a space（スコープをスペースで区切る）** ：`connection_scope`パラメーターが[IdPのAPI呼び出し](/docs/ja-jp/authenticate/identity-providers/calling-an-external-idp-api)に含まれる場合に、スコープの区切り方を決めるトグルです。デフォルトでは、スコープはカンマで区切られます。このトグルを有効にすると、スコープがスペースで区切られます。詳細については、「[IDプロバイダーのAPI呼び出しにスコープ/許可を追加する](/docs/ja-jp/authenticate/identity-providers/adding-scopes-for-an-external-idp)」をお読みください。

* **<Tooltip data-tooltip-id="react-containers-DefinitionTooltip-4" href="/docs/ja-jp/glossary?term=client-id" tip="クライアントID: Auth0から登録されたリソースに与えられる識別値。" cta="用語集の表示">Client ID</Tooltip>（クライアントID）** ：アプリケーションとしてAuth0を使う場合のクライアントIDで、認可の要求や認可コードの交換に使用されます。クライアントIDを取得するには、IDプロバイダーに登録する必要があります。

* **<Tooltip data-tooltip-id="react-containers-DefinitionTooltip-2" href="/docs/ja-jp/glossary?term=client-secret" tip="クライアントシークレット: クライアント（アプリケーション）が認可サーバーで認証するために使用するシークレット。これはクライアントと認可サーバーだけが知っているものであり、推測できないように十分にランダムである必要があります。" cta="用語集の表示">Client Secret</Tooltip>（クライアントシークレット）** ：アプリケーションとしてAuth0をを使う場合のクライアントシークレットで、認可コードの交換に使用されます。クライアントシークレットを取得するには、IDプロバイダーに登録する必要があります。

* **Fetch User Profile Script（ユーザープロファイルの取得スクリプト）** ：提供されたアクセストークンでユーザー情報URLを呼び出すためのNode.jsスクリプトです。このスクリプトの詳細については、「[ユーザープロファイルの取得スクリプト](#fetch-user-profile-script)」を参照してください。

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  カスタムのIDプロバイダーを構成するときは、Callback URLに「`https://{yourDomain}/login/callback`」を使用します。
</Callout>

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

## 認証フローを更新する

作成された接続にはデフォルトで、認可コードフローのOAuth 2.0付与タイプが割り当てられます。クライアントシークレットを保管できない公開アプリケーション（シングルページアプリケーションやネイティブアプリケーションなど）がある場合には、<Tooltip data-tooltip-id="react-containers-DefinitionTooltip-0" href="/docs/ja-jp/glossary?term=management-api" tip="Management API: 顧客が管理タスクを実行できるようにするための製品。" cta="用語集の表示">Management API</Tooltip>を使って接続を更新し、[PKCEを使用した認可コードフロー](/docs/ja-jp/get-started/authentication-and-authorization-flow/authorization-code-flow-with-pkce)が使えるようにすることができます。認可フローの詳細については、「[どのOAuth 2.0フローを使用するべきですか？](/docs/ja-jp/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>

## ユーザープロファイルの取得スクリプト

ユーザーが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`プロパティは任意ですが、強く推奨されます。返される可能性のある属性については、「[ユーザープロファイルのルート属性](/docs/ja-jp/manage-users/user-accounts/user-profiles/root-attributes/update-root-attributes-for-users)」を参照してください。

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

## カスタム接続を使用してログインする

カスタム接続でのユーザーログインには、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" />

## アイコンと表示名を変更する

IDプロバイダーのログインボタンにアイコンを追加するには、`options`オブジェクトの`icon_url`プロパティ、ログインボタンのテキストを変更するには`display_name`プロパティを[Management API](/docs/ja-jp/api/management/v2#!/Connections/patch_connections_by_id)経由で使用します。

<Warning>
  * 要求に`display_name`が含まれていない場合には、フィールドが接続の`name`値で上書きされます。
  * `display_name`と`icon_url`は、[ユニバーサルログインエクスペリエンス](/docs/ja-jp/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);
  });
  ```

  ```objc Obj-C theme={null}
  #import <Foundation/Foundation.h>

  NSDictionary *headers = @{ @"content-type": @"application/json" };

  NSData *postData = [[NSData alloc] initWithData:[@"{ "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"} }", dataUsingEncoding:NSUTF8StringEncoding]];

  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://{yourDomain}/api/v2/connections/CONNECTION-ID"]
                                                         cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                     timeoutInterval:10.0];
  [request setHTTPMethod:@"PATCH"];
  [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}/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
  ```

  ```swift Swift theme={null}
  import Foundation

  let headers = ["content-type": "application/json"]

  let postData = NSData(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"".data(using: String.Encoding.utf8)!})

  let request = NSMutableURLRequest(url: NSURL(string: "https://{yourDomain}/api/v2/connections/CONNECTION-ID")! as URL,
                                          cachePolicy: .useProtocolCachePolicy,
                                      timeoutInterval: 10.0)
  request.httpMethod = "PATCH"
  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>

## プロバイダー固有のパラメータを渡す

OAuth 2.0プロバイダーの認可エンドポイントには、プロバイダー固有のパラメーターを渡すことができます。パラメーターは静的でも動的でも構いません。

### 静的パラメーターを渡す

静的パラメーター（すべての認可要求で送信されるパラメーター）を渡すには、[Management API](/docs/ja-jp/api/management/v2#!/Connections/patch_connections_by_id)を使ってOAuth 2.0接続を構成した場合、`option`の`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);
  });
  ```

  ```objc Obj-C theme={null}
  #import <Foundation/Foundation.h>

  NSDictionary *headers = @{ @"content-type": @"application/json" };
  NSDictionary *parameters = @{ @"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" }
  };

  NSData *postData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];

  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://{yourDomain}/api/v2/connections/CONNECTION-ID"]
                                                         cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                     timeoutInterval:10.0];
  [request setHTTPMethod:@"PATCH"];
  [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}/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
  ```

  ```swift Swift theme={null}
  import Foundation

  let headers = ["content-type": "application/json"]
  let parameters = [
    "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"
    ],
  ] as [String : Any]

  let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

  let request = NSMutableURLRequest(url: NSURL(string: "https://{yourDomain}/api/v2/connections/CONNECTION-ID")! as URL,
                                          cachePolicy: .useProtocolCachePolicy,
                                      timeoutInterval: 10.0)
  request.httpMethod = "PATCH"
  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>

### 動的パラメーターを渡す

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

上の例で、`custom_param`パラメーターを認可エンドポイントに渡したい場合に、Auth0の`/authorize`エンドポイント呼び出しでパラメーターの実際の値を指定したいとします。

この場合には、`/authorize`エンドポイントが受け入れる既存の追加パラメーターの1つ（`access_type`など）を使って、それを`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);
  });
  ```

  ```objc Obj-C theme={null}
  #import <Foundation/Foundation.h>

  NSDictionary *headers = @{ @"content-type": @"application/json" };
  NSDictionary *parameters = @{ @"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" },
  };

  NSData *postData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];

  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://{yourDomain}/api/v2/connections/CONNECTION-ID"]
                                                         cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                     timeoutInterval:10.0];
  [request setHTTPMethod:@"PATCH"];
  [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}/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
  ```

  ```swift Swift theme={null}
  import Foundation

  let headers = ["content-type": "application/json"]
  let parameters = [
    "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"
    ],
  ] as [String : Any]

  let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

  let request = NSMutableURLRequest(url: NSURL(string: "https://{yourDomain}/api/v2/connections/CONNECTION-ID")! as URL,
                                          cachePolicy: .useProtocolCachePolicy,
                                      timeoutInterval: 10.0)
  request.httpMethod = "PATCH"
  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>

これで、`/authorize`エンドポイントを呼び出す際に`access_type`パラメーターにアクセスタイプを渡すことができ、その値が`custom_param`パラメーターで認可エンドポイントに渡されます。

## 追加のヘッダーを渡す

場合によっては、OAuth 2.0プロバイダーのトークンエンドポイントに追加のヘッダーを渡す必要があります。追加のヘッダーを構成するには、接続の設定を開いて、 **［Custom Headers（カスタムヘッダー）］** フィールドに、カスタムヘッダーがキーと値のペアとして含まれるJSONオブジェクトを指定します。

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

たとえば、IDプロバイダーに対して、`Authorization`ヘッダーで[Basic認証](https://en.wikipedia.org/wiki/Basic_access_authentication)の資格情報を渡す必要があるとします。このシナリオでは、 **［Custom Headers（カスタムヘッダー）］** フィールドに以下のJSONオブジェクトを指定することができます。

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

ここで、`[your credentials]`は、IDプロバイダーに送信する実際の資格情報となります。

## もっと詳しく

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