アクセストークンを取得する

ユーザーを認証する際、APIにアクセスするにはアクセストークンを要求しなければなりません。

アクセストークンを要求するには、トークンURLに対してPOST呼び出しを行います。

トークンURLへのPOSTの例


curl --request POST \
  --url 'https://{yourDomain}/oauth/token' \
  --header 'content-type: application/x-www-form-urlencoded' \
  --data grant_type=client_credentials \
  --data client_id=YOUR_CLIENT_ID \
  --data client_secret=YOUR_CLIENT_SECRET \
  --data audience=YOUR_API_IDENTIFIER

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=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER", 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=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER")

	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=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER")
  .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: 'client_credentials',
    client_id: 'YOUR_CLIENT_ID',
    client_secret: 'YOUR_CLIENT_SECRET',
    audience: 'YOUR_API_IDENTIFIER'
  })
};

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=client_credentials" dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[@"&client_id=YOUR_CLIENT_ID" dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[@"&client_secret=YOUR_CLIENT_SECRET" dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[@"&audience=YOUR_API_IDENTIFIER" 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=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER",
  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=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER"

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=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER"

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=client_credentials".data(using: String.Encoding.utf8)!)
postData.append("&client_id=YOUR_CLIENT_ID".data(using: String.Encoding.utf8)!)
postData.append("&client_secret=YOUR_CLIENT_SECRET".data(using: String.Encoding.utf8)!)
postData.append("&audience=YOUR_API_IDENTIFIER".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 これを"client_credentials"に設定します。
client_id アプリケーションのクライアントID。この値はアプリケーションの設定タブで見つけることができます。
client_secret アプリケーションのクライアントシークレット。この値はアプリケーションの設定タブで見つけることができます。使用できるアプリケーション認証方法の詳細については、「アプリケーション資格情報」をお読みください。
audience トークンのオーディエンス(ご利用のAPI)。これは、APIの[Settings(設定)]タブの**[Identifier(識別子)]**フィールドにあります。
organization 任意。要求に関連付けたい組織の名前または識別子です。詳細については「組織に対するマシンツーマシンアクセス」をお読みください。

応答

値にaccess_tokentoken_type、およびexpires_inを含むペイロードとともにHTTP 200応答が届きます。

{
  "access_token":"eyJz93a...k4laUWw",
  "token_type":"Bearer",
  "expires_in":86400
}

Was this helpful?

/

アクセストークンオーディエンスをコントロールする

ユーザー認証時、アクセストークンを要求して、対象オーディエンスとアクセスのスコープを要求に入れます。アプリケーションはアクセス要求に/authorizeエンドポイントを使います。このアクセスはアプリケーションに要求され、認証においてユーザーにも認められます。

常にデフォルトのオーディエンスを含めるようにテナントを構成できます。

トークンの使用 形式 要求されたオーディエンス 要求されたスコープ
/userinfoエンドポイント 不透明 テナント名({yourDomain})、audienceパラメーターの値なし、渡されるaudienceパラメーターなし openid
Auth0 Management API JWT Auth0 Management API v2の識別子(https://{tenant}.auth0.com/api/v2/
独自のカスタムAPI JWT Auth0 Dashboardで登録されたカスタムAPIのAPI識別子

特定の1回のインスタンスに限り、アクセストークンに複数の対象オーディエンスを入れることができます。そのためには、カスタムAPIの署名アルゴリズムをRS256に設定する必要があります。詳細については、「トークンのベストプラクティス」をお読みください。

複数オーディエンス

カスタムAPI識別子のオーディエンスとopenidのスコープを指定した場合、アクセストークンのaudクレームは文字列でなく配列となり、アクセストークンはカスタムAPIと/userinfoエンドポイントの双方に対して有効となります。単一のカスタムAPIとAuth0の/userinfoエンドポイントを使う場合は、アクセストークンのオーディエンスは2つ以上となります。

カスタムドメインとAuth0 Management API

Auth0は、トークン要求時に使ったドメインの発行者(iss)クレームとともにトークンを発行します。カスタムドメインユーザーは、カスタムドメインまたはAuth0ドメインのいずれかを使えます。

たとえば、https://login.northwind.comというカスタムドメインを使うとします。https://login.northwind.com/authorizeからアクセストークンを要求すると、トークンのissクレームはhttps://login.northwind.com/となります。しかし、https://northwind.auth0.com/authorizeからアクセストークンを要求すると、トークンのissクレームはhttps://northwind.auth0.com/となります。

Auth0 Management APIの対象オーディエンスのカスタムドメインからアクセストークンを要求する場合は、カスタムドメインからAuth0 Management APIを呼び出す必要があります。そうしないと、アクセストークンは無効とみなされます。

アクセストークンの更新

カスタムAPIのアクセストークンの有効期間は、デフォルトで86400秒間(24時間)です。トークンの有効期間が切れる前に期間を短縮できます。

アクセストークンの有効期間が切れた後は、アクセストークンを更新できます。これには、Auth0を使ってユーザーを認証するか、リフレッシュトークンを使用します。

もっと詳しく