authentication demo with Auth0


Source code step by step

Include JavaScript

This example uses the following JavaScripts.
<script src="//"></script>
<script src="/publicauth0-variables.js"></script>
<script src="/publicauth0app.js"></script>

Set up credentials (auth0-variables.js)

Add your Auto0 security credentials from Auth0 Client set up.
var AUTH0_CLIENT_ID='xxx'; 
var AUTH0_DOMAIN='xxx';
var AUTH0_CALLBACK_URL=location.href;

Invoke the Auth0 dialog to authenticate the user (auth0app.js)

Invoke the Auth0 lock dialog and store the security token in browser local storage.
var lock = new Auth0Lock(AUTH0_CLIENT_ID, AUTH0_DOMAIN, {
    auth: {
      params: { scope: 'openid email' } //Details:
    rememberLastLogin: true

  $('.btn-login').click(function(e) {

  lock.on("authenticated", function(authResult) {
    lock.getProfile(authResult.idToken, function(error, profile) {
        if (error) {
            alert("Unable to authenticate!");
        localStorage.setItem('id_token', authResult.idToken);
        // Display user information
        // enable api button
        $('.btn-api').removeAttr("disabled").text("Press me, I'm authenticated!");

Access the database using fetch and the JWT token from Auth0

When we invoke the call to our database, we set the Authorization header to contain the id_token we received from Auth0. The token must be prefixed with "Bearer ".
// We use the token from Auth0 to authenticate API calls against databases
// by setting the Authorization header using the Bearer token scheme.

  $('.btn-api').click(function(e) {
        'Authorization':'Bearer ' + localStorage.getItem("id_token")
        return response.json();
         $('#apidata').text(JSON.stringify(body, null, '  '));

Profile data

We retrieve the user profile by calling the Auth0 API.
var show_profile_info = function(profile) {
     $('.avatar').attr('src', profile.picture).show();
var retrieve_profile = function() {
    var id_token = localStorage.getItem('id_token');
    if (id_token) {
      lock.getProfile(id_token, function (err, profile) {
        if (err) {
          return alert('There was an error getting the profile: ' + err.message);
        // Display user information
        // enable api button
View Source