Prerequisites
Get access tokens
To ask Auth0 for a v2 token, perform aPOST operation to the https://{yourDomain}/oauth/token endpoint, using the credentials of the Machine-to-Machine Application you created in the prerequisite step.
The payload should be in the following format:
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/'
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);
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))
}
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();
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);
});
#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];
$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;
}
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"))
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
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()
`{yourClientSecret}` with the in the Settings tab of your Application.
The request parameters are:
| Request Parameter | Description |
|---|---|
| grant_type | Denotes which OAuth 2.0 flow you want to run. For machine to machine communication use the value client_credentials. |
| client_id | This is the value of the Client ID field of the Machine-to-Machine Application you created. You can find it on the Settings tab of your Application. |
| client_secret | This is the value of the Client Secret field of the Machine-to-Machine Application you created. You can find it at the Settings tab of your Application. |
| audience | This is the value of the Identifier field of the Auth0 Management API. You can find it at the Settings tab of the API. |
Use the
update:client_grants and create:client_grants scopes with only high-privileged applications, as they allow the client to grant further permissions to itself.{
"access_token": "eyJ...Ggg",
"expires_in": 86400,
"scope": "read:clients create:clients read:client_keys",
"token_type": "Bearer"
}
Use Auth0’s Node.js client library
As an alternative to making HTTP calls, you can use the node-auth0 library to automatically obtain tokens for the Management API.Use access tokens
To use this token, include it in theAuthorization header of your request.
curl --request POST \
--url http:///%7BmgmtApiEndpoint%7D \
--header 'authorization: Bearer {yourMgmtApiAccessToken}' \
--header 'content-type: application/json'
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);
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))
}
HttpResponse<String> response = Unirest.post("http:///%7BmgmtApiEndpoint%7D")
.header("content-type", "application/json")
.header("authorization", "Bearer {yourMgmtApiAccessToken}")
.asString();
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);
});
#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];
$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;
}
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"))
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
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()
curl --request GET \
--url 'https://{yourDomain}/api/v2/clients' \
--header 'authorization: Bearer {yourAccessToken}' \
--header 'content-type: application/json'
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);
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))
}
HttpResponse<String> response = Unirest.get("https://{yourDomain}/api/v2/clients")
.header("content-type", "application/json")
.header("authorization", "Bearer {yourAccessToken}")
.asString();
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);
});
#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];
$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;
}
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"))
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
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()
You can get the curl command for each endpoint from the Management API v2 Explorer. Go to the endpoint you want to call, and click the get curl command link at the Test this endpoint section.
Example: Python implementation
This python script gets a Management API v2 Access Token, uses it to call the Get all applications endpoint, and prints the response in the console. Before you run it make sure that the following variables hold valid values:AUDIENCE: The Identifier of theAuth0 Management API. You can find it at the Settings tab of the API.DOMAIN: The Domain of the Machine-to-Machine Application you created.CLIENT_ID: The of the Machine to Machine Application you created.CLIENT_SECRET: The Client Secret of the Machine-to-Machine Application you created.
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()