API Authorization: Asking for Access Tokens for a Client Credentials Grant

To ask Auth0 for tokens for any of your authorized client applications, perform a POST operation to the https://YOUR_AUTH0_DOMAIN/oauth/token endpoint with a payload in the following format:


curl --request POST \
  --url 'https://YOUR_AUTH0_DOMAIN/oauth/token' \
  --header 'content-type: application/json' \
  --data '{"grant_type":"client_credentials","client_id": "{CLIENT_ID}","client_secret": "{CLIENT_SECRET}","audience": "YOUR_API_IDENTIFIER"}'
var client = new RestClient("https://YOUR_AUTH0_DOMAIN/oauth/token");
var request = new RestRequest(Method.POST);
request.AddHeader("content-type", "application/json");
request.AddParameter("application/json", "{\"grant_type\":\"client_credentials\",\"client_id\": \"{CLIENT_ID}\",\"client_secret\": \"{CLIENT_SECRET}\",\"audience\": \"YOUR_API_IDENTIFIER\"}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io/ioutil"
)

func main() {

	url := "https://YOUR_AUTH0_DOMAIN/oauth/token"

	payload := strings.NewReader("{\"grant_type\":\"client_credentials\",\"client_id\": \"{CLIENT_ID}\",\"client_secret\": \"{CLIENT_SECRET}\",\"audience\": \"YOUR_API_IDENTIFIER\"}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("content-type", "application/json")

	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://YOUR_AUTH0_DOMAIN/oauth/token")
  .header("content-type", "application/json")
  .body("{\"grant_type\":\"client_credentials\",\"client_id\": \"{CLIENT_ID}\",\"client_secret\": \"{CLIENT_SECRET}\",\"audience\": \"YOUR_API_IDENTIFIER\"}")
  .asString();
var settings = {
  "async": true,
  "crossDomain": true,
  "url": "https://YOUR_AUTH0_DOMAIN/oauth/token",
  "method": "POST",
  "headers": {
    "content-type": "application/json"
  },
  "processData": false,
  "data": "{\"grant_type\":\"client_credentials\",\"client_id\": \"{CLIENT_ID}\",\"client_secret\": \"{CLIENT_SECRET}\",\"audience\": \"YOUR_API_IDENTIFIER\"}"
}

$.ajax(settings).done(function (response) {
  console.log(response);
});
var request = require("request");

var options = { method: 'POST',
  url: 'https://YOUR_AUTH0_DOMAIN/oauth/token',
  headers: { 'content-type': 'application/json' },
  body: 
   { grant_type: 'client_credentials',
     client_id: '{CLIENT_ID}',
     client_secret: '{CLIENT_SECRET}',
     audience: 'YOUR_API_IDENTIFIER' },
  json: true };

request(options, function (error, response, body) {
  if (error) throw new Error(error);

  console.log(body);
});
#import <Foundation/Foundation.h>

NSDictionary *headers = @{ @"content-type": @"application/json" };
NSDictionary *parameters = @{ @"grant_type": @"client_credentials",
                              @"client_id": @"{CLIENT_ID}",
                              @"client_secret": @"{CLIENT_SECRET}",
                              @"audience": @"YOUR_API_IDENTIFIER" };

NSData *postData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://YOUR_AUTH0_DOMAIN/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, array(
  CURLOPT_URL => "https://YOUR_AUTH0_DOMAIN/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\": \"{CLIENT_ID}\",\"client_secret\": \"{CLIENT_SECRET}\",\"audience\": \"YOUR_API_IDENTIFIER\"}",
  CURLOPT_HTTPHEADER => array(
    "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("")

payload = "{\"grant_type\":\"client_credentials\",\"client_id\": \"{CLIENT_ID}\",\"client_secret\": \"{CLIENT_SECRET}\",\"audience\": \"YOUR_API_IDENTIFIER\"}"

headers = { 'content-type': "application/json" }

conn.request("POST", "/YOUR_AUTH0_DOMAIN/oauth/token", payload, headers)

res = conn.getresponse()
data = res.read()

print(data.decode("utf-8"))
require 'uri'
require 'net/http'

url = URI("https://YOUR_AUTH0_DOMAIN/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/json'
request.body = "{\"grant_type\":\"client_credentials\",\"client_id\": \"{CLIENT_ID}\",\"client_secret\": \"{CLIENT_SECRET}\",\"audience\": \"YOUR_API_IDENTIFIER\"}"

response = http.request(request)
puts response.read_body
import Foundation

let headers = ["content-type": "application/json"]
let parameters = [
  "grant_type": "client_credentials",
  "client_id": "{CLIENT_ID}",
  "client_secret": "{CLIENT_SECRET}",
  "audience": "YOUR_API_IDENTIFIER"
]

let postData = NSJSONSerialization.dataWithJSONObject(parameters, options: nil, error: nil)

var request = NSMutableURLRequest(URL: NSURL(string: "https://YOUR_AUTH0_DOMAIN/oauth/token")!,
                                        cachePolicy: .UseProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.HTTPMethod = "POST"
request.allHTTPHeaderFields = headers
request.HTTPBody = postData

let session = NSURLSession.sharedSession()
let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    println(error)
  } else {
    let httpResponse = response as? NSHTTPURLResponse
    println(httpResponse)
  }
})

dataTask.resume()

The response will be a signed JWT (JSON Web Token) containing at least the following claims in the body:

{
  "iss": "https://YOUR_AUTH0_DOMAIN/",
  "sub": "{APP_CLIENT_ID}@clients",
  "aud": "{YOUR_API_IDENTIFIER}",
  "exp": // unix timestamp of the token's expiration date,
  "iat": // unix timestamp of the token's creation date,
  "scope": ""
}

Verifying an access token for a resource server

Access tokens will be signed using the signature method configured for the resource server, and must be verified accordingly:

For claim verification, use any recommended JWT library which validates all the standard claims returned in the token.

Authorized Client Applications

Your client app must be authorized to access your API before you can request tokens.

You can go to the Non Interactive Clients tab of your API in the APIs section of the dashboard to verify that the app you are using has been authorized to request access tokens from this API.

To add an authorized app, follow the instructions as described in API Authorization: Using the Auth0 Dashboard.

Where to Find the IDs

To find the values for the parameters referred to in this sample, go to the Clients page in the Dashboard, and select the application you want to use. There you will find these values:

  • CLIENT_ID: This is the value of the Client ID field.
  • CLIENT_SECRET: This is the value of the Client Secret field.

Also, go to the APIs section of the dashboard and select the API you are working with. There you will find this value:

  • YOUR_API_IDENTIFIER: This is the value of the Id field on the Settings tab of the API.