User Impersonation

Impersonation functionality may be disabled by default for your tenant. To check, go to the Users page in the Dashboard, select a user, and see if the Sign in as User button is displayed. If you can't see it, contact support and ask them to enable the feature for your tenant.

Often administrators need to impersonate other users for testing or troubleshooting purposes. Using impersonation the administrators can log in to an app as a specific user, see everything exactly as that user sees it, and do everything exactly as that user does it.

Auth0 provides a Sign in As feature for user impersonation, and provides the following:

  • Detailed auditing of who impersonated when.
  • Restrictions on impersonation which allows you to reject an impersonated authentication transaction based on, for instance, corporate policies around privacy and sensitive data.
  • Unlimited customization on who can impersonate who, when, depending on whatever context, using our Rules engine. In a Rule, you have access to user.impersonated (the impersonated login) and user.impersonator (the impersonating login) and you can write arbitrary Javascript to define how it works.

Any Rules that you've implemented will run when you impersonate a user, including any actions that update the user.

Use the Dashboard

Navigate to the Users page in the Auth0 Dashboard and select the user you want to log in as. Click on the Sign in as User and select the client you want to log in to using the dropdown menu.

Click Sign in as User

I can't see this button

In order to see this button the following conditions should apply:

  • Impersonation should be enabled for your tenant (see panel at the top of this page)
  • The Clients registered in the tenant must have at least one callback URL listed
  • The Clients must have the connections turned on that the users who are to be impersonated belong to

A popup displays the URL to be used in order to impersonate the user. You can choose either to copy the URL into the clipboard (white button) or open it in a separate browser tab/window (blue button).

Links for User Impersonation

Acquiring a Token

Impersonating a user using the Dashboard will not return an ID Token to your application by default. There are two ways to achieve this. You can alter the Response Type setting in the impersonation menu's Advanced Settings from Code to Token (Sign in as user -> Show Advanced Settings). Alternatively, you can add additionalParameters.scope: "openid" to the request body while calling the impersonation endpoint manually.

Advanced Settings

When impersonating a user in Dashboard, after clicking Sign in as User you will see a link to expand "Advanced Settings".

Advanced Settings

This reveals fields to make it easier to impersonate a User using the Impersonation API:

  • Response mode: GET or POST. This is only for server side apps, client side apps default to GET.
  • Response type: Code or Token. This is only for server side apps, client side apps default to Token.
  • Scope: This field will have openid in it is as default, other scopes can be added as a list using whitespace as separator.
  • State: The state is an optional parameter. Learn more about using the state parameter here.

Use the Impersonation API

You can also use the Impersonation API. The API generates a link that can be used once to log in as a specific user. To distinguish between real logins and impersonation logins, the profile of the impersonated user will contain additional impersonated and impersonator properties. For more details on how to use the API read on.

Sample Implementation

Let's assume that you have two apps, app1 and app2, and you want to impersonate the users of app2. You will need to locate the user_id of the user you wish to impersonate, either via the Dashboard or the Management API. Next, you will need to obtain an authorization code via the impersonation endpoint. Finally, you will need to exchange your code for a valid access token, and your impersonation process will be complete. You can walk through the steps below which use the example app1 and app2.

1. Find the User Id

You can use one of two methods to locate the user_id of a given user that you want to impersonate. You can either use the Management API v2 to retrieve it, or you can use the Dashboard.

Option A: Use the Management API

First, you will need an APIv2 token, if you want to retrieve the user_id via the Management API. You can get one by making a POST request to the Token endpoint. For details on how to do that refer to The Auth0 Management APIv2 Token documentation.

The Management APIv2 Token will be valid for 24 hours, so you should ask for a token everytime you make a request to the API, or vigorously handle 401 responses.

After you have a token, you will have to use the token to retrieve the user id of the user that you want to impersonate (in this example, a user of app2). You can retrieve this information with the Management API /api/v2/users endpoint.


curl --request GET \
  --url 'https://YOUR_AUTH0_DOMAIN/api/v2/users' \
  --header 'authorization: Bearer YOUR_ACCESS_TOKEN'
var client = new RestClient("https://YOUR_AUTH0_DOMAIN/api/v2/users");
var request = new RestRequest(Method.GET);
request.AddHeader("authorization", "Bearer YOUR_ACCESS_TOKEN");
IRestResponse response = client.Execute(request);
package main

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

func main() {

	url := "https://YOUR_AUTH0_DOMAIN/api/v2/users"

	req, _ := http.NewRequest("GET", url, nil)

	req.Header.Add("authorization", "Bearer YOUR_ACCESS_TOKEN")

	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://YOUR_AUTH0_DOMAIN/api/v2/users")
  .header("authorization", "Bearer YOUR_ACCESS_TOKEN")
  .asString();
var settings = {
  "async": true,
  "crossDomain": true,
  "url": "https://YOUR_AUTH0_DOMAIN/api/v2/users",
  "method": "GET",
  "headers": {
    "authorization": "Bearer YOUR_ACCESS_TOKEN"
  }
}

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

var options = { method: 'GET',
  url: 'https://YOUR_AUTH0_DOMAIN/api/v2/users',
  headers: { authorization: 'Bearer YOUR_ACCESS_TOKEN' } };

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

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

NSDictionary *headers = @{ @"authorization": @"Bearer YOUR_ACCESS_TOKEN" };

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://YOUR_AUTH0_DOMAIN/api/v2/users"]
                                                       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, array(
  CURLOPT_URL => "https://YOUR_AUTH0_DOMAIN/api/v2/users",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_HTTPHEADER => array(
    "authorization: Bearer YOUR_ACCESS_TOKEN"
  ),
));

$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 = { 'authorization': "Bearer YOUR_ACCESS_TOKEN" }

conn.request("GET", "/YOUR_AUTH0_DOMAIN/api/v2/users", headers=headers)

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

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

url = URI("https://YOUR_AUTH0_DOMAIN/api/v2/users")

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["authorization"] = 'Bearer YOUR_ACCESS_TOKEN'

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

let headers = ["authorization": "Bearer YOUR_ACCESS_TOKEN"]

var request = NSMutableURLRequest(URL: NSURL(string: "https://YOUR_AUTH0_DOMAIN/api/v2/users")!,
                                        cachePolicy: .UseProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.HTTPMethod = "GET"
request.allHTTPHeaderFields = headers

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()

Replace YOUR_ACCESS_TOKEN with the Management APIv2 token you got in the previous step.

Option B: Use the Dashboard

Alternatively, you can retrieve the user_id information from the Dashboard. Go to the Users section and look at the user's profile. The user_id is displayed under the Identity Provider Attributes section.

2. Get an Authorization Code

Before calling the call the Impersonation API you will need to generate a Bearer token. You can generate it with the Management API V1 /oauth/token endpoint with your Global Client ID and Global Client Secret which both can be found in the dashboard under Tenant Settings > Advanced.

Global Client Information

You can now send a request to the impersonation endpoint by sending an Authorization header with Bearer <TOKEN_FROM_MANAGEMENT_API_V1>.

The data part of the request should include the following:

  • protocol: the protocol to use against the identity provider. It could be oauth2 again or something else. (e.g. Office 365 uses WS-Federation, Google Apps uses OAuth2, AD will use LDAP or Kerberos).

  • impersonator_id: the user_id of the impersonator, the user from app1 that wants to impersonate a user from app2.

  • client_id: the client_id of the app that is generating the impersonation link, in this example app1.

  • additionalParameters: this is a JSON object. For a regular web app, you should set the response_type to be code, the callback_url to be the callback url to which Auth0 will redirect with the authorization code, and the scope to be the JWT claims that you want included in the JWT. For example:

    {
      "response_type": "code",
      "state": "",
      "callback_url" : "http://localhost:3001/register",
      "scope" : "openid email name user_metadata"
    }
    

The state is an optional parameter, but we strongly recommend you use it as it mitigates CSRF attacks.

The callback_url must match what is defined in your Client's Settings.

There are various possible values for scope:

  • scope: 'openid': (default) It will return, not only an opaque Access Token, but also an ID Token which is a JSON Web Token (JWT). The JWT will only contain the user id (sub claim).
  • scope: 'openid {attr1} {attr2} {attrN}': If you want only specific user's attributes to be part of the ID Token (for example, scope: 'openid name email picture').

You can get more information about this in the Scopes documentation.

Impersonation cannot be used to return JWT Access Tokens to your APIs.

Your request should look like the following:


curl --request POST \
  --url 'https://YOUR_AUTH0_DOMAIN/users/USER_ID/impersonate' \
  --header 'authorization: Bearer YOUR_ACCESS_TOKEN' \
  --header 'content-type: application/json' \
  --data '{"protocol": "PROTOCOL_TO_USE","impersonator_id": "IMPERSONATOR_ID","client_id": "YOUR_CLIENT_ID","additionalParameters":{"response_type": "code","state": ""}}'
var client = new RestClient("https://YOUR_AUTH0_DOMAIN/users/USER_ID/impersonate");
var request = new RestRequest(Method.POST);
request.AddHeader("authorization", "Bearer YOUR_ACCESS_TOKEN");
request.AddHeader("content-type", "application/json");
request.AddParameter("application/json", "{\"protocol\": \"PROTOCOL_TO_USE\",\"impersonator_id\": \"IMPERSONATOR_ID\",\"client_id\": \"YOUR_CLIENT_ID\",\"additionalParameters\":{\"response_type\": \"code\",\"state\": \"\"}}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
package main

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

func main() {

	url := "https://YOUR_AUTH0_DOMAIN/users/USER_ID/impersonate"

	payload := strings.NewReader("{\"protocol\": \"PROTOCOL_TO_USE\",\"impersonator_id\": \"IMPERSONATOR_ID\",\"client_id\": \"YOUR_CLIENT_ID\",\"additionalParameters\":{\"response_type\": \"code\",\"state\": \"\"}}")

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

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

	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/users/USER_ID/impersonate")
  .header("content-type", "application/json")
  .header("authorization", "Bearer YOUR_ACCESS_TOKEN")
  .body("{\"protocol\": \"PROTOCOL_TO_USE\",\"impersonator_id\": \"IMPERSONATOR_ID\",\"client_id\": \"YOUR_CLIENT_ID\",\"additionalParameters\":{\"response_type\": \"code\",\"state\": \"\"}}")
  .asString();
var settings = {
  "async": true,
  "crossDomain": true,
  "url": "https://YOUR_AUTH0_DOMAIN/users/USER_ID/impersonate",
  "method": "POST",
  "headers": {
    "content-type": "application/json",
    "authorization": "Bearer YOUR_ACCESS_TOKEN"
  },
  "processData": false,
  "data": "{\"protocol\": \"PROTOCOL_TO_USE\",\"impersonator_id\": \"IMPERSONATOR_ID\",\"client_id\": \"YOUR_CLIENT_ID\",\"additionalParameters\":{\"response_type\": \"code\",\"state\": \"\"}}"
}

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

var options = { method: 'POST',
  url: 'https://YOUR_AUTH0_DOMAIN/users/USER_ID/impersonate',
  headers: 
   { authorization: 'Bearer YOUR_ACCESS_TOKEN',
     'content-type': 'application/json' },
  body: 
   { protocol: 'PROTOCOL_TO_USE',
     impersonator_id: 'IMPERSONATOR_ID',
     client_id: 'YOUR_CLIENT_ID',
     additionalParameters: { response_type: 'code', state: '' } },
  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",
                           @"authorization": @"Bearer YOUR_ACCESS_TOKEN" };
NSDictionary *parameters = @{ @"protocol": @"PROTOCOL_TO_USE",
                              @"impersonator_id": @"IMPERSONATOR_ID",
                              @"client_id": @"YOUR_CLIENT_ID",
                              @"additionalParameters": @{ @"response_type": @"code", @"state": @"" } };

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

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://YOUR_AUTH0_DOMAIN/users/USER_ID/impersonate"]
                                                       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/users/USER_ID/impersonate",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => "{\"protocol\": \"PROTOCOL_TO_USE\",\"impersonator_id\": \"IMPERSONATOR_ID\",\"client_id\": \"YOUR_CLIENT_ID\",\"additionalParameters\":{\"response_type\": \"code\",\"state\": \"\"}}",
  CURLOPT_HTTPHEADER => array(
    "authorization: Bearer YOUR_ACCESS_TOKEN",
    "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 = "{\"protocol\": \"PROTOCOL_TO_USE\",\"impersonator_id\": \"IMPERSONATOR_ID\",\"client_id\": \"YOUR_CLIENT_ID\",\"additionalParameters\":{\"response_type\": \"code\",\"state\": \"\"}}"

headers = {
    'content-type': "application/json",
    'authorization': "Bearer YOUR_ACCESS_TOKEN"
    }

conn.request("POST", "/YOUR_AUTH0_DOMAIN/users/USER_ID/impersonate", payload, headers)

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

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

url = URI("https://YOUR_AUTH0_DOMAIN/users/USER_ID/impersonate")

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["authorization"] = 'Bearer YOUR_ACCESS_TOKEN'
request.body = "{\"protocol\": \"PROTOCOL_TO_USE\",\"impersonator_id\": \"IMPERSONATOR_ID\",\"client_id\": \"YOUR_CLIENT_ID\",\"additionalParameters\":{\"response_type\": \"code\",\"state\": \"\"}}"

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

let headers = [
  "content-type": "application/json",
  "authorization": "Bearer YOUR_ACCESS_TOKEN"
]
let parameters = [
  "protocol": "PROTOCOL_TO_USE",
  "impersonator_id": "IMPERSONATOR_ID",
  "client_id": "YOUR_CLIENT_ID",
  "additionalParameters": [
    "response_type": "code",
    "state": ""
  ]
]

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

var request = NSMutableURLRequest(URL: NSURL(string: "https://YOUR_AUTH0_DOMAIN/users/USER_ID/impersonate")!,
                                        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()

Replace the required values as follows:

  • YOUR_USER_ID: the user_id you retrieved at the second step (the user to impersonate)
  • YOUR_ACCESS_TOKEN: the token already retrieved at the first step
  • PROTOCOL_TO_USE: the protocol to use against the identity provider, for example oauth2
  • IMPERSONATOR_ID: the user_id of the impersonator

Upon successful authentication, a URL will be returned as response that will look like the following:

https://YOUR_APP/callback/?code=AUTHORIZATION_CODE&state=STATE_VALUE
  • https://YOUR_APP/callback is the URL you specified as callback_url (and configured in your Client's Settings)
  • state should match the state value you sent with your request
  • code is the authorization code you need

Single Page Apps

The process described applies to Regular Web Applications. In case yours is a Single Page Application (SPA) you would have to use "response_type":"token" when invoking the Impersonation API. Once you do this Auth0 will redirect to your SPA Callback URL with Access Token and ID Token in the # params. You can read more on the OAuth2 Implicit flow here.

3. Exchange Code with Token

Now you should exchange the Authorization Code you received for a token. Note that this should already be implemented if you have a regular webapp and are using OAuth Server Side flow for authenticating normal users.

If not you should send a POST request to the Token endpoint in Auth0. You will need to send the Authorization Code obtained before along with your Client ID and Client Secret.


curl --request POST \
  --url 'https://YOUR_AUTH0_DOMAIN/oauth/token' \
  --header 'content-type: application/json' \
  --data '{"client_id": "YOUR_CLIENT_ID","client_secret": "YOUR_CLIENT_SECRET","code": "AUTHORIZATION_CODE","grant_type": "authorization_code","callback_url": "https://YOUR_APP/callback"}'
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", "{\"client_id\": \"YOUR_CLIENT_ID\",\"client_secret\": \"YOUR_CLIENT_SECRET\",\"code\": \"AUTHORIZATION_CODE\",\"grant_type\": \"authorization_code\",\"callback_url\": \"https://YOUR_APP/callback\"}", 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("{\"client_id\": \"YOUR_CLIENT_ID\",\"client_secret\": \"YOUR_CLIENT_SECRET\",\"code\": \"AUTHORIZATION_CODE\",\"grant_type\": \"authorization_code\",\"callback_url\": \"https://YOUR_APP/callback\"}")

	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("{\"client_id\": \"YOUR_CLIENT_ID\",\"client_secret\": \"YOUR_CLIENT_SECRET\",\"code\": \"AUTHORIZATION_CODE\",\"grant_type\": \"authorization_code\",\"callback_url\": \"https://YOUR_APP/callback\"}")
  .asString();
var settings = {
  "async": true,
  "crossDomain": true,
  "url": "https://YOUR_AUTH0_DOMAIN/oauth/token",
  "method": "POST",
  "headers": {
    "content-type": "application/json"
  },
  "processData": false,
  "data": "{\"client_id\": \"YOUR_CLIENT_ID\",\"client_secret\": \"YOUR_CLIENT_SECRET\",\"code\": \"AUTHORIZATION_CODE\",\"grant_type\": \"authorization_code\",\"callback_url\": \"https://YOUR_APP/callback\"}"
}

$.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: 
   { client_id: 'YOUR_CLIENT_ID',
     client_secret: 'YOUR_CLIENT_SECRET',
     code: 'AUTHORIZATION_CODE',
     grant_type: 'authorization_code',
     callback_url: 'https://YOUR_APP/callback' },
  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 = @{ @"client_id": @"YOUR_CLIENT_ID",
                              @"client_secret": @"YOUR_CLIENT_SECRET",
                              @"code": @"AUTHORIZATION_CODE",
                              @"grant_type": @"authorization_code",
                              @"callback_url": @"https://YOUR_APP/callback" };

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 => "{\"client_id\": \"YOUR_CLIENT_ID\",\"client_secret\": \"YOUR_CLIENT_SECRET\",\"code\": \"AUTHORIZATION_CODE\",\"grant_type\": \"authorization_code\",\"callback_url\": \"https://YOUR_APP/callback\"}",
  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 = "{\"client_id\": \"YOUR_CLIENT_ID\",\"client_secret\": \"YOUR_CLIENT_SECRET\",\"code\": \"AUTHORIZATION_CODE\",\"grant_type\": \"authorization_code\",\"callback_url\": \"https://YOUR_APP/callback\"}"

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 = "{\"client_id\": \"YOUR_CLIENT_ID\",\"client_secret\": \"YOUR_CLIENT_SECRET\",\"code\": \"AUTHORIZATION_CODE\",\"grant_type\": \"authorization_code\",\"callback_url\": \"https://YOUR_APP/callback\"}"

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

let headers = ["content-type": "application/json"]
let parameters = [
  "client_id": "YOUR_CLIENT_ID",
  "client_secret": "YOUR_CLIENT_SECRET",
  "code": "AUTHORIZATION_CODE",
  "grant_type": "authorization_code",
  "callback_url": "https://YOUR_APP/callback"
]

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()

Replace the AUTHORIZATION_CODE with the code you received previously. Also, replace https://YOUR_APP/callback with your application's callback URL.

If the request is successful, you will get a JSON object with an Access Token. You can use this token to call the Auth0 APIs and get additional information such as the user profile.

HTTP/1.1 200 OK
Content-Type: application/json
{
  "access_token":"eyJz93a...k4laUWw",
  "id_token":"eyJ0XAi...4faeEoQ",
  "token_type":"Bearer",
  "expires_in":86400
}

Congratulations, you are done!

Keep Reading