リソース所有者のパスワードフローを使ってAPIを呼び出す
Auth0は、Authentication APIを使用して、アプリがリソース所有者のパスワードフロー(Resource Owner Password Grant、またはROPGと呼ばれることもある)を簡単に実装できるようにします。APIを直接呼び出す方法については、このまま続けてお読みください。
前提条件
このチュートリアルを始める前に:
[Regular Web Apps(通常のWebアプリ)]の[Application Type(アプリケーションタイプ)]を選択します。
{https://yourApp/callback}
の[Allowed Callback(許可されているコールバック)]URLを追加します。このフィールドを未定義にすることはできません。未定義にすると、エラーメッセージが返されます。アプリケーションの[Grant Types(付与タイプ)]に[Password(パスワード)]が含まれていることを確認します。詳細については、「付与タイプを更新する」をお読みください。
アプリケーションでリフレッシュトークンを使用できるようにするには、アプリケーションの[Grant Types(付与タイプ)]に[Refresh Token(リフレッシュトークン)]が含まれていることを確認してください。詳細については、「付与タイプを更新する」をお読みください。リフレッシュトークンの詳細については、「リフレッシュトークン」をお読みください。
APIがリフレッシュトークンを受信して、以前のトークンの有効期限が切れたときに新しいトークンを取得できるようにする場合は、[Allow Offline Access(オフラインアクセスの許可)]を有効にします。
Set up a connection(接続のセットアップ)
ユーザー名とパスワードによるユーザー認証が可能な接続であることを確認します(例:データベース接続、またはAD/LDAP、ADFS、Entra IDエンタープライズ接続)。
特定の接続にのみ影響を与えるように、ルールを更新または無効化します。リソース所有者のパスワー付与をテストしている際に
access_denied
エラーが発生した場合、アクセス制御ルールが原因である可能性があります。
ステップ
テナントを構成する: テナントのデフォルト接続を設定します。
トークンを要求する: 認可コードをトークンと交換します。
APIを呼び出す: 取得したアクセストークンを使ってAPIを呼び出します。
リフレッシュトークン: 既存のトークンが期限切れになったら、リフレッシュトークンを使用して新しいトークンを要求します。
任意:レルムの対応を構成する
任意:MFAの構成
任意:攻撃防御の設定
テナントを構成する
リソース所有者のパスワードフローは、ユーザー名とパスワードでユーザーを認証できる接続に依存しているため、テナントのデフォルト接続を設定する必要があります。
[Auth0 Dashboard]>[Tenant Settings(テナント設定)]に移動し、下にスクロールして[Default Directory(デフォルトディレクトリ)]設定を見つけます。
使用する接続の名前を入力します。ユーザー名とパスワードによるユーザー認証が可能であることを確認します。
トークンを要求する
APIを呼び出すには、まずユーザーの資格情報を取得しなければなりません。これは、通常、インタラクティブな形式で行います。アプリケーションは、受け取った資格情報をトークンと交換しなければなりません。これを行うには、トークンURLにPOST
する必要があります。
トークンURLへのPOSTの例
curl --request POST \
--url 'https://{yourDomain}/oauth/token' \
--header 'content-type: application/x-www-form-urlencoded' \
--data grant_type=password \
--data 'username={username}' \
--data 'password={password}' \
--data 'audience={yourApiIdentifier}' \
--data scope=read:sample \
--data 'client_id={yourClientId}' \
--data 'client_secret={yourClientSecret}'
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=password&username=%7Busername%7D&password=%7Bpassword%7D&audience=%7ByourApiIdentifier%7D&scope=read%3Asample&client_id={yourClientId}&client_secret=%7ByourClientSecret%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=password&username=%7Busername%7D&password=%7Bpassword%7D&audience=%7ByourApiIdentifier%7D&scope=read%3Asample&client_id={yourClientId}&client_secret=%7ByourClientSecret%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=password&username=%7Busername%7D&password=%7Bpassword%7D&audience=%7ByourApiIdentifier%7D&scope=read%3Asample&client_id={yourClientId}&client_secret=%7ByourClientSecret%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: 'password',
username: '{username}',
password: '{password}',
audience: '{yourApiIdentifier}',
scope: 'read:sample',
client_id: '{yourClientId}',
client_secret: '{yourClientSecret}'
})
};
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=password" dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[@"&username={username}" dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[@"&password={password}" dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[@"&audience={yourApiIdentifier}" dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[@"&scope=read:sample" dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[@"&client_id={yourClientId}" dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[@"&client_secret={yourClientSecret}" 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=password&username=%7Busername%7D&password=%7Bpassword%7D&audience=%7ByourApiIdentifier%7D&scope=read%3Asample&client_id={yourClientId}&client_secret=%7ByourClientSecret%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=password&username=%7Busername%7D&password=%7Bpassword%7D&audience=%7ByourApiIdentifier%7D&scope=read%3Asample&client_id={yourClientId}&client_secret=%7ByourClientSecret%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=password&username=%7Busername%7D&password=%7Bpassword%7D&audience=%7ByourApiIdentifier%7D&scope=read%3Asample&client_id={yourClientId}&client_secret=%7ByourClientSecret%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=password".data(using: String.Encoding.utf8)!)
postData.append("&username={username}".data(using: String.Encoding.utf8)!)
postData.append("&password={password}".data(using: String.Encoding.utf8)!)
postData.append("&audience={yourApiIdentifier}".data(using: String.Encoding.utf8)!)
postData.append("&scope=read:sample".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)!)
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 |
これをpassword に設定します。 |
username |
ユーザーが入力したユーザー名です。 |
password |
ユーザーが入力したパスワードです。 |
client_id |
アプリケーションのクライアントIDです。この値は[Application Settings(アプリケーションの設定)]にあります。 |
client_assertion |
アプリケーション資格情報のある署名付きアサーションを含んだJWTです。アプリケーションの認証方法が秘密鍵JWTである場合は必須です。 |
client_assertion_type |
値はurn:ietf:params:oauth:client-assertion-type:jwt-bearer です。アプリケーションの認証方法が秘密鍵JWTである場合は必須です。 |
client_secret |
アプリケーションのクライアントシークレットです。アプリケーションの認証方法がクライアントシークレットである場合は必須です。[Application Settings(アプリケーションの設定)]はPost またはBasic です。アプリケーションの信頼性が高くない場合(SPAなど)には、このパラメーターを設定してはいけません。 |
audience |
トークンのオーディエンス、つまりはAPIです。これはAPIの[Settings(設定)]タブの**[Identifier(識別子)]**フィールドにあります。 |
scope |
認可を要求したいスコープを指定します。これによって、受け取りたいクレーム(またはユーザー属性)が決定されます。スペース区切りでリストする必要があります。ユーザーについて任意の標準OpenID Connect(OIDC)スコープを要求できます。たとえば、profile やemail 、名前空間形式に準拠したカスタムクレーム、呼び出すAPIが対応しているスコープ(read:contacts など)を要求できます。リフレッシュトークンを取得するには、offline_access を含めます([Application Settings(アプリケーションの設定)])で__[Allow Offline Access(オフラインアクセスを許可する)]__フィールドが有効になっていることを確認してください)。 |
応答
すべてが成功すると、access_token
、refresh_token
、id_token
、token_type
、およびexpires_in
の値を含むペイロードとともにHTTP 200
応答を受信します。
{
"access_token": "eyJz93a...k4laUWw",
"refresh_token": "GEbRxBN...edjnXbL",
"id_token": "eyJ0XAi...4faeEoQ",
"token_type": "Bearer",
"expires_in": 36000
}
Was this helpful?
リソース所有者のパスワードのフローと標準スコープ
パスワードの提供でフルアクセス権が与えられるため、パスワードベースの交換ではすべてのスコープにアクセスできるようになります。たとえば、要求にAPIスコープを含めなくても、アクセストークンにはすべてのAPIスコープが含まれます。同様に、要求にopenid
スコープだけを含めた場合でも、openid
標準のOpenID Connectスコープがすべて返されます。これらの場合、応答にはscope
パラメーターが含まれ、その値は発行されたスコープのリストになります。
ユーザー情報をIDトークンなしで取得する
ユーザー情報が必要な場合は、要求にopenid
スコープを含めます。APIがRS256
を署名アルゴリズムとして使用している場合は、アクセストークンに/userinfo
が有効なオーディエンスとして含まれ、これを使うと/userinfoエンドポイントを呼び出してユーザーのクレームを取得することができます。
APIを呼び出す
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
応答を受信します。
{
"access_token": "eyJ...MoQ",
"expires_in": 86400,
"scope": "openid offline_access",
"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?
すべてのルールが実行された後、トークンでスコープが使用可能になります。
レルムの対応を構成する
Auth0の拡張機能付与には、リソース所有者パスワード付与と似たような機能性がありますが、(別の接続にマッピングしている)別のユーザーディレクトリにして、フローで使用するものを個別に指定できるようになってます。
このバリエーションを使用するには、次のことを行う必要があります。
grant_type
要求パラメーターをhttp://auth0.com/oauth/grant-type/password-realm
に設定します。realm
という追加の要求パラメーターを送信し、それをユーザーが所属するレルムの名前に設定します。たとえば、内部の従業員用にemployees
という名前のデータベース接続を設定しており、そのユーザーがその接続に属している場合、realm
をemployees
に設定します。
レルムとしての接続
データベース接続やパスワードレス接続、AD/LDAP、ADFS、Azure Active Directoryのエンタープライズ接続など、アクティブなアプリケーションに対応している接続はすべて、レルムとして構成できます。
MFAの構成
リソース所有者パスワードフローの使用が必要な反面、より強固な認証が要求される場合には、多要素認証(MFA)を追加することができます。方法については、「MFAでリソース所有者のパスワードフローを使って認証する」をお読みください。
攻撃防御の設定
リソース所有者のパスワードフローと総当たり攻撃から保護する機能を併用した場合には、一部の防御機能が無効になる可能性があります。ただし、いくつかの問題は回避することができます。詳細については、「リソース所有者のパスワードフローと攻撃防御のよくある不具合を回避する」をお読みください。