Get Access Tokens for Single Page Applications

You cannot get Access Tokens using the other methods for single page applications (SPAs) because we use the Client Secret which is sensitive information (same as a password) and cannot be exposed to the browser.

You can still get tokens for the Management API from the frontend, but with some limitations. You can access only certain scopes and update only the logged-in user's data. You can access the following scopes, and hence endpoints:

Endpoint Scope for current user
GET /api/v2/users/{id} read:current_user
GET /api/v2/users/{id}/enrollments read:current_user
POST/api/v2/users/{id}/identities update:current_user_identities
DELETE /api/v2/users/{id}/identities/{provider}/{user_id} update:current_user_identities
PATCH /api/v2/users/{id} update:current_user_metadata
PATCH /api/v2/users/{id} create:current_user_metadata
DELETE /api/v2/users/{id}/multifactor/{provider} delete:current_user_metadata
POST /api/v2/device-credentials create:current_user_device_credentials
DELETE /api/v2/device-credentials/{id} delete:current_user_device_credentials

If you get an Access Token that contains the scope read:current_user, you can retrieve the information of the currently logged-in user (the one that the token was issued for).

Example

You can get a token, for example to retrieve the information of the currently logged-in user, using the Authorization endpoint. This is where you redirect your users to login or sign up.

In the example below, we want to use the GET User by ID endpoint to retrieve the full profile information of the logged-in user. To do so, first we will authenticate our user (using the Implicit grant) and retrieve the token(s).

https://YOUR_AUTH0_DOMAIN/authorize?
  audience=https://YOUR_AUTH0_DOMAIN/api/v2/
  &scope=read:current_user
  &response_type=token%20id_token
  &client_id=YOUR_CLIENT_ID
  &redirect_uri=https://YOUR_APP/callback
  &nonce=CRYPTOGRAPHIC_NONCE
  &state=OPAQUE_VALUE

If you are not familiar with authentication for single page applications, see Authentication for Client-side Web Apps.

Notice the following:

  • We set the audience to https://YOUR_AUTH0_DOMAIN/api/v2/
  • We asked for the scope read:current_user
  • We set the response_type to id_token token so Auth0 will sent us both an ID Token and an Access Token

If we decode the Access Token and review its contents we can see the following:

{
  "iss": "https://YOUR_AUTH0_DOMAIN/",
  "sub": "auth0|5a620d29a840170a9ef43672",
  "aud": "https://YOUR_AUTH0_DOMAIN/api/v2/",
  "iat": 1521031317,
  "exp": 1521038517,
  "azp": "YOUR_CLIENT_ID",
  "scope": "read:current_user"
}

Notice that the aud is set to your tenant's API URI, the scope to read:current_user, and the sub to the user ID of the logged in user.

Once you have the Access Token, you can use it to call the endpoint. Use the Access Token in the Authorization header of the request.


curl --request GET \
  --url 'https://YOUR_AUTH0_DOMAIN/api/v2/users/USER_ID' \
  --header 'authorization: Bearer YOUR_MGMT_API_ACCESS_TOKEN'
var client = new RestClient("https://YOUR_AUTH0_DOMAIN/api/v2/users/USER_ID");
var request = new RestRequest(Method.GET);
request.AddHeader("authorization", "Bearer YOUR_MGMT_API_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/USER_ID"

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

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

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://YOUR_AUTH0_DOMAIN/api/v2/users/USER_ID"]
                                                       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/USER_ID",
  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_MGMT_API_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_MGMT_API_ACCESS_TOKEN" }

conn.request("GET", "/YOUR_AUTH0_DOMAIN/api/v2/users/USER_ID", 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/USER_ID")

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_MGMT_API_ACCESS_TOKEN'

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

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

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

Keep reading