本番環境のManagement APIアクセストークンの取得
本番環境に定期的かつ頻繁な呼び出しを行うには、バックエンドでトークンを自動的に提供するプロセスを構築(して、擬似的に無期限のトークンに)します。
前提条件
アクセストークンの取得
Auth0にManagement API v2トークンを求めるには、前提条件のステップで作成したM2Mアプリケーションの資格情報を使用して、POST
操作をhttps://{yourDomain}/oauth/token
エンドポイントに実行します。
ペイロードは次の形式でなければなりません。
curl --request POST \
--url 'https://{yourDomain}/oauth/token' \
--header 'content-type: application/x-www-form-urlencoded' \
--data grant_type=client_credentials \
--data 'client_id={yourClientId}' \
--data 'client_secret={yourClientSecret}' \
--data 'audience=https://{yourDomain}/api/v2/'
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={yourClientId}&client_secret=%7ByourClientSecret%7D&audience=https%3A%2F%2F{yourDomain}%2Fapi%2Fv2%2F", 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={yourClientId}&client_secret=%7ByourClientSecret%7D&audience=https%3A%2F%2F{yourDomain}%2Fapi%2Fv2%2F")
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={yourClientId}&client_secret=%7ByourClientSecret%7D&audience=https%3A%2F%2F{yourDomain}%2Fapi%2Fv2%2F")
.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: '{yourClientId}',
client_secret: '{yourClientSecret}',
audience: 'https://{yourDomain}/api/v2/'
})
};
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={yourClientId}" dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[@"&client_secret={yourClientSecret}" dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[@"&audience=https://{yourDomain}/api/v2/" 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={yourClientId}&client_secret=%7ByourClientSecret%7D&audience=https%3A%2F%2F{yourDomain}%2Fapi%2Fv2%2F",
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={yourClientId}&client_secret=%7ByourClientSecret%7D&audience=https%3A%2F%2F{yourDomain}%2Fapi%2Fv2%2F"
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={yourClientId}&client_secret=%7ByourClientSecret%7D&audience=https%3A%2F%2F{yourDomain}%2Fapi%2Fv2%2F"
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={yourClientId}".data(using: String.Encoding.utf8)!)
postData.append("&client_secret={yourClientSecret}".data(using: String.Encoding.utf8)!)
postData.append("&audience=https://{yourDomain}/api/v2/".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?
アプリケーションの設定タブで必ず`{yourClientSecret}`
をクライアントシークレットに更新します。
要求パラメーター:
要求パラメーター | 説明 |
---|---|
grant_type | 実行したいOAuth 2.0フローを示します。マシンツーマシン通信については、client_credentials の値を使用します。 |
client_id | これは作成したマシンツーマシンアプリケーションの クライアントID フィールドの値です。アプリケーションの設定タブで見つけることができます。 |
client_secret | これは作成したマシンツーマシンアプリケーションの クライアントシークレット フィールドの値です。アプリケーションの設定タブで見つけることができます。 |
audience | これはAuth0 Management API の 識別子 フィールドの値です。APIの設定タブで見つけることができます。 |
応答には署名済みJWT、有効期限、付与されたスコープ、およびトークンタイプが含まれます。
{
"access_token": "eyJ...Ggg",
"expires_in": 86400,
"scope": "read:clients create:clients read:client_keys",
"token_type": "Bearer"
}
Was this helpful?
上記から、アクセストークンの期限が24時間(86400秒)後に切れること、アプリケーションの読み取りと作成が許可されていること、そしてベアラーアクセストークンであることがわかります。
Auth0のNode.jsクライアントライブラリーの使用
HTTP呼び出しの代わりに、node-auth0ライブラリーを使用して自動的にManagement APIのトークンを取得することもできます。
アクセストークンの使用
このトークンを使用するには、要求のAuthorization
ヘッダーに含めます。
curl --request POST \
--url http:///%7BmgmtApiEndpoint%7D \
--header 'authorization: Bearer {yourMgmtApiAccessToken}' \
--header 'content-type: application/json'
Was this helpful?
var client = new RestClient("http:///%7BmgmtApiEndpoint%7D");
var request = new RestRequest(Method.POST);
request.AddHeader("content-type", "application/json");
request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}");
IRestResponse response = client.Execute(request);
Was this helpful?
package main
import (
"fmt"
"net/http"
"io/ioutil"
)
func main() {
url := "http:///%7BmgmtApiEndpoint%7D"
req, _ := http.NewRequest("POST", url, nil)
req.Header.Add("content-type", "application/json")
req.Header.Add("authorization", "Bearer {yourMgmtApiAccessToken}")
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("http:///%7BmgmtApiEndpoint%7D")
.header("content-type", "application/json")
.header("authorization", "Bearer {yourMgmtApiAccessToken}")
.asString();
Was this helpful?
var axios = require("axios").default;
var options = {
method: 'POST',
url: 'http:///%7BmgmtApiEndpoint%7D',
headers: {
'content-type': 'application/json',
authorization: 'Bearer {yourMgmtApiAccessToken}'
}
};
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 {yourMgmtApiAccessToken}" };
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http:///%7BmgmtApiEndpoint%7D"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
[request setHTTPMethod:@"POST"];
[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 => "http:///%7BmgmtApiEndpoint%7D",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_HTTPHEADER => [
"authorization: Bearer {yourMgmtApiAccessToken}",
"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.HTTPConnection("")
headers = {
'content-type': "application/json",
'authorization': "Bearer {yourMgmtApiAccessToken}"
}
conn.request("POST", "%7BmgmtApiEndpoint%7D", headers=headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))
Was this helpful?
require 'uri'
require 'net/http'
url = URI("http:///%7BmgmtApiEndpoint%7D")
http = Net::HTTP.new(url.host, url.port)
request = Net::HTTP::Post.new(url)
request["content-type"] = 'application/json'
request["authorization"] = 'Bearer {yourMgmtApiAccessToken}'
response = http.request(request)
puts response.read_body
Was this helpful?
import Foundation
let headers = [
"content-type": "application/json",
"authorization": "Bearer {yourMgmtApiAccessToken}"
]
let request = NSMutableURLRequest(url: NSURL(string: "http:///%7BmgmtApiEndpoint%7D")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "POST"
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?
たとえば、すべてのアプリケーションを取得するには、以下を使用します。
curl --request GET \
--url 'https://{yourDomain}/api/v2/clients' \
--header 'authorization: Bearer {yourAccessToken}' \
--header 'content-type: application/json'
Was this helpful?
var client = new RestClient("https://{yourDomain}/api/v2/clients");
var request = new RestRequest(Method.GET);
request.AddHeader("content-type", "application/json");
request.AddHeader("authorization", "Bearer {yourAccessToken}");
IRestResponse response = client.Execute(request);
Was this helpful?
package main
import (
"fmt"
"net/http"
"io/ioutil"
)
func main() {
url := "https://{yourDomain}/api/v2/clients"
req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("content-type", "application/json")
req.Header.Add("authorization", "Bearer {yourAccessToken}")
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://{yourDomain}/api/v2/clients")
.header("content-type", "application/json")
.header("authorization", "Bearer {yourAccessToken}")
.asString();
Was this helpful?
var axios = require("axios").default;
var options = {
method: 'GET',
url: 'https://{yourDomain}/api/v2/clients',
headers: {'content-type': 'application/json', authorization: 'Bearer {yourAccessToken}'}
};
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 {yourAccessToken}" };
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://{yourDomain}/api/v2/clients"]
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://{yourDomain}/api/v2/clients",
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 {yourAccessToken}",
"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("")
headers = {
'content-type': "application/json",
'authorization': "Bearer {yourAccessToken}"
}
conn.request("GET", "/{yourDomain}/api/v2/clients", 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://{yourDomain}/api/v2/clients")
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 {yourAccessToken}'
response = http.request(request)
puts response.read_body
Was this helpful?
import Foundation
let headers = [
"content-type": "application/json",
"authorization": "Bearer {yourAccessToken}"
]
let request = NSMutableURLRequest(url: NSURL(string: "https://{yourDomain}/api/v2/clients")! 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?
例:Pythonの実装
このPythonスクリプトはManagement API v2のアクセストークンを取得し、すべてのアプリケーション取得エンドポイントの呼び出しに使用して、コンソールに応答を出力します。
実行する前に、以下の変数が有効な値であることを確認してください。
AUDIENCE
:Auth0 Management API
のIdentifier(識別子)。APIの[Settings(設定)]タブにあります。DOMAIN
:作成したM2MアプリケーションのDomain(ドメイン)。CLIENT_ID
:作成したM2MアプリケーションのClient ID(クライアントID)。CLIENT_SECRET
:作成したM2MアプリケーションのClient Secret(クライアントシークレット)。
def main():
import json, requests
from requests.exceptions import RequestException, HTTPError, URLRequired
# Configuration Values
domain = 'YOUR_DOMAIN'
audience = f'https://{domain}/api/v2/'
client_id = 'YOUR_CLIENT_ID'
client_secret = 'YOUR_CLIENT_SECRET'
grant_type = "client_credentials" # OAuth 2.0 flow to use
# Get an Access Token from Auth0
base_url = f"https://{domain}"
payload = {
'grant_type': grant_type,
'client_id': client_id,
'client_secret': client_secret,
'audience': audience
}
response = requests.post(f'{base_url}/oauth/token', data=payload)
oauth = response.json()
access_token = oauth.get('access_token')
# Add the token to the Authorization header of the request
headers = {
'Authorization': f'Bearer {access_token}',
'Content-Type': 'application/json'
}
# Get all Applications using the token
try:
res = requests.get(f'{base_url}/api/v2/clients', headers=headers)
print(res.json())
except HTTPError as e:
print(f'HTTPError: {str(e.code)} {str(e.reason)}')
except URLRequired as e:
print(f'URLRequired: {str(e.reason)}')
except RequestException as e:
print(f'RequestException: {e}')
except Exception as e:
print(f'Generic Exception: {e}')
# Standard boilerplate to call the main() function.
if __name__ == '__main__':
main()
Was this helpful?