ハイブリッドフローを使用してAPIを呼び出す
Auth0では、以下を使用することでアプリは簡単に認可コードフローを実装できるようになります。
Authentication API:独自のソリューションを構築したい場合は、このまま読み続けて、APIを直接呼び出す方法を学習してください。
前提条件
このチュートリアルを始める前に:
適切な[Application Type(アプリケーションタイプ)]を選択します。
{https://yourApp/callback}
の[Allowed Callback URL(許可されているコールバックURL)]を追加します。アプリケーションの[Grant Types(付与タイプ)]に[Implicit(暗黙的)]と[Authorization Code(認可コード)]が必ず含まれていることを確認してください。詳細については、「付与タイプを更新する」をお読みください。
アプリケーションでリフレッシュトークンを使用できるようにするには、アプリケーションの[Grant Types(付与タイプ)]に[Refresh Token(リフレッシュトークン)]が含まれていることを確認してください。詳細については、「付与タイプを更新する」をお読みください。リフレッシュトークンの詳細については、「リフレッシュトークン」をお読みください。
APIがリフレッシュトークンを受信して、以前のトークンの有効期限が切れたときに新しいトークンを取得できるようにする場合は、[Allow Offline Access(オフラインアクセスの許可)]を有効にします。
ステップ
ユーザーを認可する: ユーザーの認可を要求し、認可コードと一緒にアプリにリダイレクトします。
トークンを要求する: 認可コードをトークンと交換します。
APIを呼び出す: 取得したアクセストークンを使ってAPIを呼び出します。
リフレッシュトークン: 既存のトークンが期限切れになったら、リフレッシュトークンを使用して新しいトークンを要求します。
ユーザーを認可する
この手順には、以下のようなプロセスが含まれます。
ユーザーを認証する
認証を行うために、ユーザーをIDプロバイダーへリダイレクトする
有効なシングルサインオン(SSO)セッションを確認する
以前に同意を得ていない場合は、要求された権限レベルについてユーザーの同意を得る
ユーザーを認可するには、アプリがユーザーを認可URLに送信する必要があります。
認可URLの例
https://{yourDomain}/authorize?
response_type=YOUR_RESPONSE_TYPE&
response_mode=form_post&
client_id={yourClientId}&
redirect_uri={https://yourApp/callback}&
scope=SCOPE&
audience=API_AUDIENCE&
state=STATE&
nonce=NONCE
Was this helpful?
パラメーター
ユーザーを認可するためにカスタムのAPIを呼び出すときは、
- オーディエンスパラメーターを含めなければなりません。 - ターゲットAPIでサポートされている追加のスコープを含めることができます。
パラメーター名 | 説明 |
---|---|
response_type |
Auth0が返す資格情報の種類を示します(コードまたはトークン)。このフローでは、値はcode を含む必要がありますが、id_token 、token 、id_token token を含むこともできます。特に、id_token はIDトークンを返し、token はアクセストークンを返します。 |
response_mode |
応答パラメーターが返される方法を指定します。安全保護のため、値はform_post にする必要があります。このモードでは、応答パラメーターは、HTTP POSTメソッドを介して送信され、application/x-www-form-urlencoded フォーマットを使用して本文でエンコードされるHTMLフォーム値としてエンコードされます。 |
client_id |
アプリケーションのクライアントID。これは、アプリケーション設定で見つけることができます。 |
redirect_uri |
認可がユーザーにより付与された後にAuth0がブラウザーをリダイレクトするURL。認可コードは、code URLパラメーターで利用できます。アプリケーション設定で有効なコールバックURLとしてこのURLを指定する必要があります。 警告: OAuth 2.0の仕様に従って、Auth0はハッシュの後、すべてを削除し、フラグメントを受け付けません。 |
scope |
返したいクレーム(またはユーザー属性)を決定する、認可を要求したいスコープを指定します。スペースで区切る必要があります。profile またはemail などのユーザーに関する標準OpenID Connect(OIDC)スコープ、名前空間形式に従ったカスタムクレーム、ターゲットAPIがサポートするスコープ(例、read:contacts )を要求できます。offline_access を含めてリフレッシュトークンを取得できます(Allow Offline Access(オフラインアクセスの許可)フィールドがアプリケーション設定で有効になっていることを確認してください)。 |
audience |
WebアプリケーションがアクセスするAPIの一意の識別子。このチュートリアルの前提条件の一環として作成したAPIのSettings(設定)の**Identifier(識別子)**値を使用します。 |
state |
(推奨)Auth0がリダイレクトしてアプリケーションに戻る際に含まれ、アプリが初期要求に追加する不透明な任意の英数字の文字列。クロスサイトリクエストフォージェリ(CSRF)攻撃を防止するためにこの値を使用する方法については、状態パラメーターを使ってCSRF攻撃を軽減するをご覧ください。 |
nonce |
トークンリプレイ攻撃を防ぐために使用される、アプリが初期要求に追加し、Auth0がIDトークンに含める暗号的にランダムな文字列。 |
organization |
(任意)ユーザーを認証する時に使用する組織のID。提供されない場合、アプリケーションは**Display Organization Prompt(組織のプロンプトを表示)**に設定され、ユーザーは、認証時に組織名を入力できます。 |
invitation |
(任意)組織の招待のチケットID。Organizationにメンバーを招待する場合、ユーザーが招待を受け入れたとき、アプリケーションは、invitation およびorganization のキー/値ペアを転送することで、招待の受け入れを処理する必要があります。 |
たとえば、アプリにログインを追加する際の認可URLのHTMLスニペットは、以下のようになります。
<a href="https://{yourDomain}/authorize?
response_type=code id_token token&
client_id={yourClientId}&
redirect_uri={https://yourApp/callback}&
scope=appointments%20contacts&
audience=appointments:api&
state=xyzABC123&
nonce=eq...hPmz">
Sign In
</a>
Was this helpful?
応答
すべてが成功すると、HTTP 302
応答を受け取ります。要求された資格情報は本文にエンコードされます。
HTTP/1.1 302 Found
Content-Type: application/x-www-form-urlencoded
code=AUTHORIZATION_CODE&
access_token=ey...MhPw
&expires_in=7200
&token_type=Bearer
id_token=eyJ...acA&
state=xyzABC123
Was this helpful?
返される値は、response_type
として何を要求したかによって異なります。
応答タイプ | コンポーネント |
---|---|
code |
認可コード |
id_token |
IDトークン |
token |
アクセストークン(およびexpires_in とtoken_type 値) |
id_token token |
IDトークン、アクセストークン(およびexpires_in とtoken_type 値) |
Auth0は、認可URLへの呼び出しに含めた状態値も返します。
IDトークンをデコードして解析すると、c_hash
という追加のクレームが含まれていることがわかります。これにはcode
のハッシュが含まれています。このクレームは、IDトークンがcode
と同時に発行される場合に必須であり、検証する必要があります。
IDトークンのヘッダー内の
alg
クレームで指定されたハッシュアルゴリズムを使用して、code
のASCII表現のオクテットをハッシュ化します。ハッシュの左半分をBase64urlエンコードします。
結果が
c_hash
の値と一致することを確認します。
トークンを要求する
取得した認可コードは、トークンと交換する必要があります。前の手順で抽出した認可コード(code
)を使用して、トークンURLにPOST
する必要があります。
このステップで受け取るアクセス トークンは、APIを呼び出す際に使用します。このトークンは、チュートリアルの前のステップで受け取ったアクセストークンとは別に保管するようにしてください。
トークンURLへのPOSTの例
curl --request POST \
--url 'https://{yourDomain}/oauth/token' \
--header 'content-type: application/x-www-form-urlencoded' \
--data grant_type=authorization_code \
--data 'client_id={yourClientId}' \
--data 'client_secret={yourClientSecret}' \
--data 'code=yourAuthorizationCode}' \
--data 'redirect_uri={https://yourApp/callback}'
Was this helpful?
var client = new RestClient("https://{yourDomain}/oauth/token");
var request = new RestRequest(Method.POST);
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded", "grant_type=authorization_code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&code=yourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Was this helpful?
package main
import (
"fmt"
"strings"
"net/http"
"io/ioutil"
)
func main() {
url := "https://{yourDomain}/oauth/token"
payload := strings.NewReader("grant_type=authorization_code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&code=yourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}")
req, _ := http.NewRequest("POST", url, payload)
req.Header.Add("content-type", "application/x-www-form-urlencoded")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := ioutil.ReadAll(res.Body)
fmt.Println(res)
fmt.Println(string(body))
}
Was this helpful?
HttpResponse<String> response = Unirest.post("https://{yourDomain}/oauth/token")
.header("content-type", "application/x-www-form-urlencoded")
.body("grant_type=authorization_code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&code=yourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}")
.asString();
Was this helpful?
var axios = require("axios").default;
var options = {
method: 'POST',
url: 'https://{yourDomain}/oauth/token',
headers: {'content-type': 'application/x-www-form-urlencoded'},
data: new URLSearchParams({
grant_type: 'authorization_code',
client_id: '{yourClientId}',
client_secret: '{yourClientSecret}',
code: 'yourAuthorizationCode}',
redirect_uri: '{https://yourApp/callback}'
})
};
axios.request(options).then(function (response) {
console.log(response.data);
}).catch(function (error) {
console.error(error);
});
Was this helpful?
#import <Foundation/Foundation.h>
NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" };
NSMutableData *postData = [[NSMutableData alloc] initWithData:[@"grant_type=authorization_code" dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[@"&client_id={yourClientId}" dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[@"&client_secret={yourClientSecret}" dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[@"&code=yourAuthorizationCode}" dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[@"&redirect_uri={https://yourApp/callback}" dataUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://{yourDomain}/oauth/token"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
[request setHTTPMethod:@"POST"];
[request setAllHTTPHeaderFields:headers];
[request setHTTPBody:postData];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(@"%@", error);
} else {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
NSLog(@"%@", httpResponse);
}
}];
[dataTask resume];
Was this helpful?
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://{yourDomain}/oauth/token",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "grant_type=authorization_code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&code=yourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}",
CURLOPT_HTTPHEADER => [
"content-type: application/x-www-form-urlencoded"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
Was this helpful?
import http.client
conn = http.client.HTTPSConnection("")
payload = "grant_type=authorization_code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&code=yourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}"
headers = { 'content-type': "application/x-www-form-urlencoded" }
conn.request("POST", "/{yourDomain}/oauth/token", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))
Was this helpful?
require 'uri'
require 'net/http'
require 'openssl'
url = URI("https://{yourDomain}/oauth/token")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Post.new(url)
request["content-type"] = 'application/x-www-form-urlencoded'
request.body = "grant_type=authorization_code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&code=yourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}"
response = http.request(request)
puts response.read_body
Was this helpful?
import Foundation
let headers = ["content-type": "application/x-www-form-urlencoded"]
let postData = NSMutableData(data: "grant_type=authorization_code".data(using: String.Encoding.utf8)!)
postData.append("&client_id={yourClientId}".data(using: String.Encoding.utf8)!)
postData.append("&client_secret={yourClientSecret}".data(using: String.Encoding.utf8)!)
postData.append("&code=yourAuthorizationCode}".data(using: String.Encoding.utf8)!)
postData.append("&redirect_uri={https://yourApp/callback}".data(using: String.Encoding.utf8)!)
let request = NSMutableURLRequest(url: NSURL(string: "https://{yourDomain}/oauth/token")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error)
} else {
let httpResponse = response as? HTTPURLResponse
print(httpResponse)
}
})
dataTask.resume()
Was this helpful?
パラメーター
パラメーター名 | 説明 |
---|---|
grant_type |
authorization_code に設定します。 |
code |
このチュートリアルの前の手順で取得したauthorization_code です。 |
client_id |
アプリケーションのクライアントIDです。この値は[Application Settings(アプリケーションの設定)]で見つけることができます。 |
client_secret |
アプリケーションのクライアントシークレットです。この値は[Application Settings(アプリケーションの設定)]で見つけることができます。アプリケーションの認証方法については、「アプリケーションの資格情報」をお読みください。 |
redirect_uri |
アプリケーションの設定で指定されている有効なコールバックURLです。このチュートリアルの前の手順で認可URLに渡されたredirect_uri と完全に一致しなければなりません。これは、URLエンコードする必要があります。 |
応答
すべてが成功すると、access_token
、fresh_token
、id_token
、およびtoken_type
の値を含むペイロードとともにHTTP 200
応答を受信します。
{
"access_token": "eyJz93a...k4laUWw",
"refresh_token": "GEbRxBN...edjnXbL",
"id_token": "eyJ0XAi...4faeEoQ",
"token_type": "Bearer"
}
Was this helpful?
IDトークンには、デコードして抽出する必要があるユーザー情報が含まれています。
アクセストークンは、Auth0認証APIの/userinfoエンドポイントまたは別のAPIを呼び出すために使用されます。独自のAPIを呼び出す場合にAPIが最初に行うのは、アクセストークンを検証することです。
リフレッシュトークンは、アクセストークンまたはIDトークンの期限が切れたときに、新しいトークンの取得に使用されます。refresh_token
は、offline_access
スコープを含め、DashboardでAPIの[Allow Offline Access(オフラインアクセスの許可)]を有効にした場合にのみ、応答内に表示されます。
APIを呼び出す
通常のWebアプリケーション(または同様のケースで、アプリケーションの資格情報を安全に保存できる場合)からAPIを呼び出すには、アプリケーションは、取得したアクセストークンをベアラートークンとしてHTTP要求の認可ヘッダーで渡さなければなりません。
curl --request GET \
--url https://myapi.com/api \
--header 'authorization: Bearer {accessToken}' \
--header 'content-type: application/json'
Was this helpful?
var client = new RestClient("https://myapi.com/api");
var request = new RestRequest(Method.GET);
request.AddHeader("content-type", "application/json");
request.AddHeader("authorization", "Bearer {accessToken}");
IRestResponse response = client.Execute(request);
Was this helpful?
package main
import (
"fmt"
"net/http"
"io/ioutil"
)
func main() {
url := "https://myapi.com/api"
req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("content-type", "application/json")
req.Header.Add("authorization", "Bearer {accessToken}")
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.get("https://myapi.com/api")
.header("content-type", "application/json")
.header("authorization", "Bearer {accessToken}")
.asString();
Was this helpful?
var axios = require("axios").default;
var options = {
method: 'GET',
url: 'https://myapi.com/api',
headers: {'content-type': 'application/json', authorization: 'Bearer {accessToken}'}
};
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",
@"authorization": @"Bearer {accessToken}" };
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://myapi.com/api"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
[request setHTTPMethod:@"GET"];
[request setAllHTTPHeaderFields:headers];
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://myapi.com/api",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => [
"authorization: Bearer {accessToken}",
"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("myapi.com")
headers = {
'content-type': "application/json",
'authorization': "Bearer {accessToken}"
}
conn.request("GET", "/api", headers=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://myapi.com/api")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Get.new(url)
request["content-type"] = 'application/json'
request["authorization"] = 'Bearer {accessToken}'
response = http.request(request)
puts response.read_body
Was this helpful?
import Foundation
let headers = [
"content-type": "application/json",
"authorization": "Bearer {accessToken}"
]
let request = NSMutableURLRequest(url: NSURL(string: "https://myapi.com/api")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers
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?
リフレッシュトークン
このチュートリアルに従って次の作業を完了している場合、あなたはすでにリフレッシュ トークンを受け取っています。
オフラインアクセスを許可するように、APIを構成する。
認可エンドポイントを通じて認証要求を開始するときに、
offline_access
スコープを含める。
リフレッシュトークンを使って新しいアクセストークンを取得することができます。通常、新しいアクセストークンが必要になるのは、以前のトークンの期限が切れたときや、新しいリソースに初めてアクセスする場合に限られます。APIを呼び出すたびにエンドポイントを呼び出して新しいアクセストークンを取得するのは、良くない習慣です。Auth0は、同じIPから同じトークンを使って実行できるエンドポイントへの要求数を、レート制限を通じて調整します。
トークンを更新するには、grant_type=refresh_token
を使用して、認証APIの/oauth/token
エンドポイントに対してPOST
要求を送信します。
トークンURLへのPOSTの例
curl --request POST \
--url 'https://{yourDomain}/oauth/token' \
--header 'content-type: application/x-www-form-urlencoded' \
--data grant_type=refresh_token \
--data 'client_id={yourClientId}' \
--data 'refresh_token={yourRefreshToken}'
Was this helpful?
var client = new RestClient("https://{yourDomain}/oauth/token");
var request = new RestRequest(Method.POST);
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded", "grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Was this helpful?
package main
import (
"fmt"
"strings"
"net/http"
"io/ioutil"
)
func main() {
url := "https://{yourDomain}/oauth/token"
payload := strings.NewReader("grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D")
req, _ := http.NewRequest("POST", url, payload)
req.Header.Add("content-type", "application/x-www-form-urlencoded")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := ioutil.ReadAll(res.Body)
fmt.Println(res)
fmt.Println(string(body))
}
Was this helpful?
HttpResponse<String> response = Unirest.post("https://{yourDomain}/oauth/token")
.header("content-type", "application/x-www-form-urlencoded")
.body("grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D")
.asString();
Was this helpful?
var axios = require("axios").default;
var options = {
method: 'POST',
url: 'https://{yourDomain}/oauth/token',
headers: {'content-type': 'application/x-www-form-urlencoded'},
data: new URLSearchParams({
grant_type: 'refresh_token',
client_id: '{yourClientId}',
refresh_token: '{yourRefreshToken}'
})
};
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/x-www-form-urlencoded" };
NSMutableData *postData = [[NSMutableData alloc] initWithData:[@"grant_type=refresh_token" dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[@"&client_id={yourClientId}" dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[@"&refresh_token={yourRefreshToken}" dataUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://{yourDomain}/oauth/token"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
[request setHTTPMethod:@"POST"];
[request setAllHTTPHeaderFields:headers];
[request setHTTPBody:postData];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(@"%@", error);
} else {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
NSLog(@"%@", httpResponse);
}
}];
[dataTask resume];
Was this helpful?
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://{yourDomain}/oauth/token",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D",
CURLOPT_HTTPHEADER => [
"content-type: application/x-www-form-urlencoded"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
Was this helpful?
import http.client
conn = http.client.HTTPSConnection("")
payload = "grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D"
headers = { 'content-type': "application/x-www-form-urlencoded" }
conn.request("POST", "/{yourDomain}/oauth/token", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))
Was this helpful?
require 'uri'
require 'net/http'
require 'openssl'
url = URI("https://{yourDomain}/oauth/token")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Post.new(url)
request["content-type"] = 'application/x-www-form-urlencoded'
request.body = "grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D"
response = http.request(request)
puts response.read_body
Was this helpful?
import Foundation
let headers = ["content-type": "application/x-www-form-urlencoded"]
let postData = NSMutableData(data: "grant_type=refresh_token".data(using: String.Encoding.utf8)!)
postData.append("&client_id={yourClientId}".data(using: String.Encoding.utf8)!)
postData.append("&refresh_token={yourRefreshToken}".data(using: String.Encoding.utf8)!)
let request = NSMutableURLRequest(url: NSURL(string: "https://{yourDomain}/oauth/token")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error)
} else {
let httpResponse = response as? HTTPURLResponse
print(httpResponse)
}
})
dataTask.resume()
Was this helpful?
パラメーター
パラメーター名 | 説明 |
---|---|
grant_type |
これをrefresh_token に設定します。 |
client_id |
アプリケーションのクライアントID。この値はアプリケーション設定で確認できます。 |
refresh_token |
使用するリフレッシュトークン。 |
scope |
(任意)要求されたスコープの権限をスペースで区切ったリスト。送信されない場合は、元のスコープが使用されます。送信する場合は、スコープを減らして要求することができます。これはURLでエンコードされている必要があります。 |
応答
すべてが成功すると、新しいaccess_token
、秒単位の有効期間(expires_in
)、付与されたscope
値、およびtoken_type
を含むペイロードとともにHTTP 200
応答を受信します。最初のトークンのスコープにopenid
が含まれている場合、応答には新しいid_token
も含まれます。
{
"access_token": "eyJ...MoQ",
"expires_in": 86400,
"scope": "openid offline_access",
"id_token": "eyJ...0NE",
"token_type": "Bearer"
}
Was this helpful?
サンプルユースケース
トークンをカスタマイズする
ルールを使用して、アクセストークンで返されたスコープを変更し、クレームをアクセスとIDトークンに追加することができます。(ルールの詳細については、「Auth0ルール」をお読みください。)これを行うには、ユーザーの認証後に実行される次のルールを追加します。
exports.onExecutePostLogin = async (event, api) => {
// Add custom claims to Access Token and ID Token
api.accessToken.setCustomClaim('https://foo/bar', 'value');
api.idToken.setCustomClaim('https://fiz/baz', 'some other value');
// Modify the scope of the Access Token
api.accessToken.addScope('foo');
api.accessToken.addScope('bar');
};
Was this helpful?
すべてのルールが実行された後、トークンでスコープが使用可能になります。