jQuery Login

Sample Project

Download a sample project specific to this tutorial configured with your Auth0 API Keys.

System Requirements
  • jQuery 3.2.1
Show requirements

Before you start

This guide walks you through setting up authentication and authorization in your jQuery apps with Auth0. If you are new to Auth0, check our Overview. For a complete picture of authentication and authorization for all Single Page Applications, check our SPA + API documentation.

Auth0 uses OAuth. If you want to learn more about the OAuth flows used by Single Page Applications, read about Authentication for Client-side Web Apps.

Get Your Application Keys

When you signed up for Auth0, you created a new client.

Your application needs some details about this client to communicate with Auth0. You can get these details from the Settings section for your client in the Auth0 dashboard.

You need the following information:

  • Client ID
  • Domain

If you download the sample from the top of this page, these details are filled out for you. If you have more than one client in your account, the sample comes with the values for your Default App.

App Dashboard

Configure Callback URLs

A callback URL is a URL in your application where Auth0 redirects the user after they have authenticated.

You need to whitelist the callback URL for your app in the Allowed Callback URLs field in your Client Settings. If you do not set any callback URL, your users will see a mismatch error when they log in.

If you are following along with the sample project, Allowed Callback URLs should be set to http://localhost:3000, http://localhost:5000.

Install auth0.js

You need the auth0.js library to integrate Auth0 into your application.

Install auth0.js using npm or yarn.

# installation with npm
npm install --save auth0-js

# installation with yarn
yarn add auth0-js

Once you install auth0.js, add it to your build system or bring it in to your project with a script tag.

<script type="text/javascript" src="node_modules/auth0-js/build/auth0.js"></script>

If you do not want to use a package manager, you can retrieve auth0.js from Auth0's CDN.

<script src="https://cdn.auth0.com/js/auth0/8.10.1/auth0.min.js"></script>

Add Authentication with Auth0

The Auth0 hosted login page is the easiest way to set up authentication in your application. We recommend using the Auth0 hosted login page for the best experience, best security and the fullest array of features. This guide will use it to provide a way for your users to log in to your jQuery application.

You can also embed the Lock widget directly in your application. If you use this method, some features, such as single sign-on, will not be accessible. To learn how to embed the Lock widget in your application, follow the Embedded Login sample.

When a user logs in, Auth0 returns three items:

You can use these items in your application to set up and manage authentication.

Create an Authentication Service

Add a new file and name it app.js. You can use the file to create and manage an instance of the auth0.WebAuth object and hold logic to hide and display DOM elements.

// app.js

$('document').ready(function() {

  var webAuth = new auth0.WebAuth({
    domain: AUTH0_DOMAIN,
    clientID: AUTH0_CLIENT_ID,
    redirectUri: AUTH0_CALLBACK_URL,
    audience: 'https://' + AUTH0_DOMAIN + '/userinfo',
    responseType: 'token id_token',
    scope: 'openid'
  });

  var loginBtn = $('#btn-login');

  loginBtn.click(function(e) {
    e.preventDefault();
    webAuth.authorize();
  });

});

Checkpoint: Add a button with the btn-login class to your app. This will call the authorize method from auth0.js, so you can see the login page.

hosted login

Finish the Authentication Functions

Add more functions to the app.js file to handle authentication in the app.

The example below shows the following methods:

  • handleAuthentication: looks for the result of authentication in the URL hash. Then, the result is processed with the parseHash method from auth0.js
  • setSession: stores the user's access token, ID token, and the access token's expiry time in browser storage
  • logout: removes the user's tokens and expiry time from browser storage
  • isAuthenticated: checks whether the expiry time for the user's access token has passed
// app.js

$('document').ready(function() {

  // ...
  var loginStatus = $('.container h4');
  var loginView = $('#login-view');
  var homeView = $('#home-view');

  // buttons and event listeners
  var homeViewBtn = $('#btn-home-view');
  var loginBtn = $('#btn-login');
  var logoutBtn = $('#btn-logout');

  homeViewBtn.click(function() {
    homeView.css('display', 'inline-block');
    loginView.css('display', 'none');
  });

  loginBtn.click(function(e) {
    e.preventDefault();
    webAuth.authorize();
  });

  logoutBtn.click(logout);

  function setSession(authResult) {
    // Set the time that the access token will expire at
    var expiresAt = JSON.stringify(
      authResult.expiresIn * 1000 + new Date().getTime()
    );
    localStorage.setItem('access_token', authResult.accessToken);
    localStorage.setItem('id_token', authResult.idToken);
    localStorage.setItem('expires_at', expiresAt);
  }

  function logout() {
    // Remove tokens and expiry time from localStorage
    localStorage.removeItem('access_token');
    localStorage.removeItem('id_token');
    localStorage.removeItem('expires_at');
    displayButtons();
  }

  function isAuthenticated() {
    // Check whether the current time is past the
    // access token's expiry time
    var expiresAt = JSON.parse(localStorage.getItem('expires_at'));
    return new Date().getTime() < expiresAt;
  }

  function handleAuthentication() {
    webAuth.parseHash(function(err, authResult) {
      if (authResult && authResult.accessToken && authResult.idToken) {
        window.location.hash = '';
        setSession(authResult);
        loginBtn.css('display', 'none');
        homeView.css('display', 'inline-block');
      } else if (err) {
        homeView.css('display', 'inline-block');
        console.log(err);
        alert(
          'Error: ' + err.error + '. Check the console for further details.'
        );
      }
      displayButtons();
    });
  }

  function displayButtons() {
    if (isAuthenticated()) {
      loginBtn.css('display', 'none');
      logoutBtn.css('display', 'inline-block');
      loginStatus.text('You are logged in!');
    } else {
      loginBtn.css('display', 'inline-block');
      logoutBtn.css('display', 'none');
      loginStatus.text('You are not logged in! Please log in to continue.');
    }
  }

});

Provide a Login Control

Provide a template with controls for the user to log in and out.

<!-- index.html -->

<div class="content">
  <nav class="navbar navbar-default">
    <div class="container-fluid">
      <div class="navbar-header">
        <a class="navbar-brand" href="#">Auth0 - jQuery</a>

        <button id="btn-home-view" class="btn btn-primary btn-margin">
            Home
        </button>

        <button id="btn-login" class="btn btn-primary btn-margin">
            Log In
        </button>

        <button id="btn-logout" class="btn btn-primary btn-margin">
            Log Out
        </button>

      </div>
    </div>
  </nav>

  <main class="container">
    <!-- home view -->
    <div id="home-view">
      <h4></h4>
    </div>
    
  </main>

</div>

This example uses Bootstrap styles. You can use any style library, or not use one at all.

Depending on whether the user is authenticated or not, they see the Log In or Log Out button. The click event listeners on the buttons make calls to functions in the app.js file to let the user log in or out. When the user clicks Log In, the user is redirected to the Auth0 hosted login page.

The Auth0 hosted login page uses the Lock widget. To learn more about the hosted login page, see the hosted login page documentation. To customize the look and feel of the Lock widget, see the customization options documentation.

Process the Authentication Result

When a user authenticates at the Auth0 hosted login page, they are redirected to your application. Their URL contains a hash fragment with their authentication information. The handleAuthentication function in the app.js file processes the hash.

Call the handleAuthentication function in the app.js file. The function processes the authentication hash while your app loads.

// app.js

$('document').ready(function() {

  // ...
  handleAuthentication();
});

Next Tutorial
2. User Profile
Use Auth0 for FREECreate free Account