jQuery OAuth2 API Authorization

At some point, your APIs may need to allow limited access to users, servers, or servers on behalf of users. This tutorial demonstrates how to use the OAuth 2.0 authorization features of Auth0 to give your applications (or third-party applications) limited access to your APIs on behalf of users. For more information, check out our documentation.

Caution: Preview Feature

This is a preview feature and may be changed prior to launch. You are advised to contact support before using this feature in a production application as future changes could be breaking.

Compatability Warning

The OAuth2 API Authorization quickstart tutorial uses new OAuth2 as a Service features in Auth0. As a result, not everything is fully backwards compatible, including 3rd party hosted Lock. This quickstart tutorial uses Auth0 hosted Lock instead.

Before Starting

1. Enable OAuth2 as a Service

To execute the steps in this tutorial, you will need to enable a flag under your Account Settings. This will allow you to opt-in and out of this feature at any point in time while it remains under preview.

  1. Open the Dashboard and browse to Account Settings -> Advanced.
  2. Scroll down to the Settings section and turn on the flag "OAuth2 as a Service (Preview)"

You will see that the API section is now displayed on your sidebar.

2. Create an Application

Create an Auth0 account (or login) and add an authentication client instance from the dashboard. Once you create your client, you will be provided with credentials (Domain, Client ID, and Client Secret) which should be stored somewhere safe (do not commit this information to your git repo!). You can download the sample after you login and it will be pre-configured with your Default App credentials.

App Dashboard

Be sure to register the URL of your app in the Allowed Callback URLs in your Application Settings.

3. Create a Resource Server (API)

Create an Auth0 account (or login) naviagate to the APIs section in Dashboard. Click the Create API button and provide a Name and Identifier for your API. You must choose the RS256 signing algorithm. Once it is created, navigate to the Scopes tab and create the applicable scopes for your API.

Create API Update Scopes

Take note of the API Identifier and Scopes you defined in the Dashboard, as they will be used later.

Configuring Your Application

1. Initialize

First, add Auth0's JavaScript SDK to your jQuery application.

<script src="https://cdn.auth0.com/w2/auth0-7.2.min.js"></script>

Create a new Auth0 client instance as follows:

var auth0 = new Auth0({
    domain:       'YOUR_NAMESPACE',
    clientID:     'YOUR_CLIENT_ID',
    callbackURL:  '{YOUR APP URL}'

Note that the callbackURL must be defined in Dashboard for your client.

2. Login

Within your application's HTML, create an element with id btn-login. Then trigger the login on any of your enabled Connections with the following code. This will direct the user to the /authorize URL, which is the first step in the Implicit Grant OAuth flow. You can read more about API Authorization here.

// trigger login to Auth0 when the Login button is clicked
$('#btn-login').click(function(e) {
      responseType: 'id_token token',
      scope: 'openid profile {API SCOPES}',
      audience: '{API IDENTIFIER}'

The audience parameter should contain your API identifier from the Dashboard. The scope parameter should include one or more scopes you defined in the Dashboard for your API, in addition to any of the standard openid scopes.

3. Processing the Callback

Once you have succesfully authenticated, Auth0 will redirect to the callbackURL parameter defined in the constructor. Auth0 will append a few extra parameters after a hash on the URL. These include an access_token and an id_token, both JSON Web Tokens (JWTs). You can parse the hash and grab the tokens as follows:

var result = auth0.parseHash(window.location.hash);

if (result && result.idToken) {
    // keep these in localStorage to use later
    localStorage.setItem('access_token', result.accessToken);
    localStorage.setItem('id_token', result.idToken);
    auth0.getProfile(result.idToken, function (err, profile) {
        alert('hello ' + profile.name);

} else if (result && result.error) {
  alert('error: ' + result.error);

The access_token will be used to make an Authenticated API call. Remember that using response_type: token means that you cannot get a refresh_token. The id_token can be used in your application for basic profile data. If you want to retrieve additional profile data for the user, you can use the userinfo endpoint with the access_token in the Authorization header. For more information, see our API documentation.

4. Making an Authenticated API Call

Use the access_token to invoke your Resource Server (API):

var accessToken = localStorage.getItem('accessToken');
fetch('{API URL}', {
  method: 'get',
  headers: new Headers({
    'Content-Type': 'application/json',
    'Authorization' : 'Bearer ' + accessToken
}).then(function(response) {
  response.text().then(function(t) {
    if (response.status !== 200) {
    alert('API Response: ' + JSON.stringify(JSON.parse(t)));
}).catch(function(err) {
  alert('error: ' + err);

The Resource Server (API) should be configured to verify the JWT and any claims contained within it. Because the Resource Server is utilizing the RS256 signature method, tokens are signed using Auth0's private key for your account. Verification is done using the corresponding public key, which can be found at the following standard JWKS (JSON Web Key set) URL: [https://YOUR_NAMESPACE/.well-known/jwks.json]. You can use any recommended JWT library to validate the standard claims returned in the token. These details are outside the scope of this quickstart tutorial. More information can be found in our documentation.

5. Log Out

In this implementation, a logout involves simply deleting the saved tokens from localStorage and redirecting the user to the home page:

window.location.href = "/";

Previous Tutorial
11. Customizing Lock
Try Auth0 for FREECreate free Account