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

最も一般的なIDプロバイダー(IdP)は、Auth0 DashboardAuth0 Marketplaceから利用できます。ただし、Auth0 Dashboardでは、任意のOAuth 2.0プロバイダーをカスタムソーシャル接続として追加することもできます。

  1. Dashboardから、[Authentication(認証)]>[Social(ソーシャル)]に移動します。

  2. [Create Connection(接続を作成)]を選択し、リストの下部に移動してから[Create Custom(カスタムを作成)]を選択します。

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

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

  • Authorization URL(認可URL):URLユーザーがログインのためにリダイレクトされるURLです。

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

  • Scope(スコープ):認可要求と一緒に送信するscopeパラメーターです。複数のスコープはスペースで区切ります。

  • Separate scopes using a space(スコープをスペースで区切る)connection_scopeパラメーターがIdPのAPI呼び出しに含まれる場合に、スコープの区切り方を決めるトグルです。デフォルトでは、スコープはカンマで区切られます。このトグルを有効にすると、スコープがスペースで区切られます。詳細については、「IDプロバイダーのAPI呼び出しにスコープ/許可を追加する」をお読みください。

  • Client ID(クライアントID):アプリケーションとしてAuth0を使う場合のクライアントIDで、認可の要求や認可コードの交換に使用されます。クライアントIDを取得するには、IDプロバイダーに登録する必要があります。

  • Client Secret(クライアントシークレット):アプリケーションとしてAuth0をを使う場合のクライアントシークレットで、認可コードの交換に使用されます。クライアントシークレットを取得するには、IDプロバイダーに登録する必要があります。

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

カスタム接続を作成すると、[Application(アプリケーション)]ビューが表示され、その接続がAuth0のレート制限ポリシーの対象となります。ここでは、接続を表示したいアプリケーションを有効または無効にすることができます。

認証フローを更新する

作成された接続にはデフォルトで、認可コードフローのOAuth 2.0付与タイプが割り当てられます。クライアントシークレットを保管できない公開アプリケーション(シングルページアプリケーションやネイティブアプリケーションなど)がある場合には、Management APIを使って接続を更新し、PKCEを使用した認可コードフローが使えるようにすることができます。認可フローの詳細については、「どのOAuth 2.0フローを使用するべきですか?

  1. /get-connections-by-idエンドポイントに対してGET要求を行います。応答は以下のようになります。

    {
      "id": "[connectionID]",
      "options": {
        "email": true,
        "scope": [
          "email",
          "profile"
        ],
        "profile": true
      },
      "strategy": "google-oauth2",
      "name": "google-oauth2",
      "is_domain_connection": false,
      "enabled_clients": [
        "[yourAuth0Domain]"
      ],
      "realms": [
        "google-oauth2"
      ]
    }

    Was this helpful?

    /

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

  3. optionsオブジェクトを使ってPATCH要求を行い、"pkce_enabled":trueを追加します。

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

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

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

Was this helpful?

/

返されたプロファイルにuser_idプロパティは必須です。emailプロパティは任意ですが、強く推奨されます。返される可能性のある属性については、「ユーザープロファイルのルート属性」を参照してください。

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

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

カスタム接続でのユーザーログインには、Auth0の標準的なメカニズムであれば何でも使用することができます。直接リンクは以下のようになります。

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

Was this helpful?

/

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

IDプロバイダーのログインボタンにアイコンを追加するには、optionsオブジェクトのicon_urlプロパティ、ログインボタンのテキストを変更するにはdisplay_nameプロパティをManagement API経由で使用します。


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" }, "enabled_clients": [ "..." ] }, "display_name": "Connection Name"'

Was this helpful?

/
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\" }, \"enabled_clients\": [ \"...\" ] }, \"display_name\": \"Connection Name\"", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);

Was this helpful?

/
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\" }, \"enabled_clients\": [ \"...\" ] }, \"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))

}

Was this helpful?

/
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\" }, \"enabled_clients\": [ \"...\" ] }, \"display_name\": \"Connection Name\"")
  .asString();

Was this helpful?

/
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" }, "enabled_clients": [ "..." ] }, "display_name": "Connection Name"'
};

axios.request(options).then(function (response) {
  console.log(response.data);
}).catch(function (error) {
  console.error(error);
});

Was this helpful?

/
#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" }, "enabled_clients": [ "..." ] }, "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];

Was this helpful?

/
$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\" }, \"enabled_clients\": [ \"...\" ] }, \"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;
}

Was this helpful?

/
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\" }, \"enabled_clients\": [ \"...\" ] }, \"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"))

Was this helpful?

/
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\" }, \"enabled_clients\": [ \"...\" ] }, \"display_name\": \"Connection Name\""

response = http.request(request)
puts response.read_body

Was this helpful?

/
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" }, "enabled_clients": [ "..." ] }, "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()

Was this helpful?

/

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

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

静的パラメーターを渡す

静的パラメーター(すべての認可要求で送信されるパラメーター)を渡すには、Management APIを使ってOAuth 2.0接続を構成した場合、optionauthParams要素を使用することができます。以下の呼び出しは、すべての認可要求について、custom_paramの静的パラメーターをcustom.param.valueに設定します。


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" }, "enabled_clients": [ "..." ] }'

Was this helpful?

/
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\" }, \"enabled_clients\": [ \"...\" ] }", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);

Was this helpful?

/
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\" }, \"enabled_clients\": [ \"...\" ] }")

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

}

Was this helpful?

/
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\" }, \"enabled_clients\": [ \"...\" ] }")
  .asString();

Was this helpful?

/
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'
    },
    enabled_clients: ['...']
  }
};

axios.request(options).then(function (response) {
  console.log(response.data);
}).catch(function (error) {
  console.error(error);
});

Was this helpful?

/
#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" },
                              @"enabled_clients": @[ @"..." ] };

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

Was this helpful?

/
$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\" }, \"enabled_clients\": [ \"...\" ] }",
  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;
}

Was this helpful?

/
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\" }, \"enabled_clients\": [ \"...\" ] }"

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

Was this helpful?

/
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\" }, \"enabled_clients\": [ \"...\" ] }"

response = http.request(request)
puts response.read_body

Was this helpful?

/
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"
  ],
  "enabled_clients": ["..."]
] 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()

Was this helpful?

/

動的パラメーターを渡す

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

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

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


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" }, "enabled_clients": [ "..." ] }'

Was this helpful?

/
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\" }, \"enabled_clients\": [ \"...\" ] }", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);

Was this helpful?

/
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\" }, \"enabled_clients\": [ \"...\" ] }")

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

}

Was this helpful?

/
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\" }, \"enabled_clients\": [ \"...\" ] }")
  .asString();

Was this helpful?

/
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'
    },
    enabled_clients: ['...']
  }
};

axios.request(options).then(function (response) {
  console.log(response.data);
}).catch(function (error) {
  console.error(error);
});

Was this helpful?

/
#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" },
                              @"enabled_clients": @[ @"..." ] };

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

Was this helpful?

/
$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\" }, \"enabled_clients\": [ \"...\" ] }",
  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;
}

Was this helpful?

/
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\" }, \"enabled_clients\": [ \"...\" ] }"

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

Was this helpful?

/
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\" }, \"enabled_clients\": [ \"...\" ] }"

response = http.request(request)
puts response.read_body

Was this helpful?

/
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"
  ],
  "enabled_clients": ["..."]
] 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()

Was this helpful?

/

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

追加のヘッダーを渡す

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

{
    "Header1" : "Value",
    "Header2" : "Value"
}

Was this helpful?

/

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

{
  "Authorization": "Basic [your credentials]"
}

Was this helpful?

/

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

もっと詳しく