Cordova

Community maintained

Sample Project

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

System Requirements
  • NodeJS 5
  • Cordova 5.4+
Show requirements

To integrate Auth0 in a hybrid Cordova application, you can use the @auth0/cordova package available on npm. This package provides an interface with Cordova which allows you to use the Proof Key for Code Exchange (PKCE) spec. PKCE is recommended for native and hybrid applications to mitigate the threat of authorization code interception.

Please note that PKCE authentication requires testing on either an emulated or real device. Attempting authentication when testing in the browser will fail because PKCE requires a device browser.

Get Your Application Keys

When you signed up for Auth0, you were invited to create a new client.

There are some details about this client that your application needs to know about to properly communicate with Auth0, including your Client ID and Domain. You can retrieve these values from the settings area for your client in the Auth0 dashboard.

Please note that if you download the samples available for this tutorial, these keys will be pre-populated for you. If you have created more than one client in your account, the sample will come with the values for your Default App.

App Dashboard

Configure Callback URLs

A callback URL is a URL in your application where Auth0 redirects to after the user has authenticated. You need to whitelist a callback URL for your app in the Callback URLs field in your Client Settings. If no callback URLs are set, a mismatch error will be displayed when a user logs in.

The Callback URL to be used for your application includes your app's package ID which is found in the config.xml file for your app.

Go to the Application Settings section in your Auth0 dashboard and set your Callback URL in the Allowed Callback URLs box.

# replace YOUR_PACKAGE_ID with your app package ID
YOUR_PACKAGE_ID://YOUR_AUTH0_DOMAIN/cordova/YOUR_PACKAGE_ID/callback

Add file as an allowed origin to the Allowed Origins (CORS) box.

file://*

Lastly, be sure that the Client Type for your application is set to Native in the client settings.

Install the Dependencies

The required dependencies for using Auth0 in a Cordova application are auth0.js and auth0-cordova. Install them with npm or yarn.

# installation with npm
npm install auth0-js @auth0/cordova --save

# installation with yarn
yarn add auth0-js @auth0/cordova

Add Cordova Plugins

You must install the SafariViewController plugin from Cordova to be able to show Auth0's hosted login page. The downloadable sample project already has this plugin added, but if you are adding Auth0 to your own application, install the plugin via the command line.

cordova plugin add cordova-plugin-safariviewcontroller

The CustomURLScheme plugin from Cordova is also required to handle redirects properly. The sample project has it already, but if you're adding Auth0 to your own project, install this plugin as well.

# replace YOUR_PACKAGE_ID with your app identifier
cordova plugin add cordova-plugin-customurlscheme --variable URL_SCHEME={YOUR_PACKAGE_ID} --variable ANDROID_SCHEME={YOUR_PACKAGE_ID} --variable ANDROID_HOST=YOUR_AUTH0_DOMAIN --variable ANDROID_PATHPREFIX=/cordova/{YOUR_PACKAGE_ID}/callback

Modify config.xml

Add <preference name="AndroidLaunchMode" value="singleTask" /> to your config.xml. This will allow the Auth0 dialog to properly redirect back to your app.

Set Up URL Redirects

Use the onRedirectUri method from auth0-cordova when your app loads to properly handle redirects after authentication.

var Auth0Cordova =  require('@auth0/cordova');
var App = require('./App');

function main() {
  var app = new App();
  function intentHandler(url) {
    Auth0Cordova.onRedirectUri(url);
  }
  window.handleOpenURL = intentHandler;
  app.run('#app');
}

document.addEventListener('deviceready', main);

Note: The code samples shown in this tutorial assume that your app is using some kind of bundler like browserify or webpack to make npm modules available in a client application. The downloadable sample for this tutorial uses webpack but you are free to use whichever bundler you like.

Create a Main App File and Configure Auth0

Create a main application file and initialize Auth0 in it. This file can also serve as the place where you change what is rendered in the app. This file needs methods for logging users in and out, as well as checking their authentication state. Be sure to replace YOUR_PACKAGE_ID with the identifier for your app in the configuration block.

var Auth0 = require('auth0-js');
var Auth0Cordova = require('@auth0/cordova');

function getAllBySelector(arg) {
  return document.querySelectorAll(arg);
}

function getBySelector(arg) {
  return document.querySelector(arg);
}

function getById(id) {
  return document.getElementById(id);
}

function getAllByClassName(className) {
  return document.getElementsByClassName(className);
}

function App() {
  this.auth0 = new Auth0.Authentication({
    domain: 'YOUR_AUTH0_DOMAIN',
    clientID: 'YOUR_CLIENT_ID'
  });
  this.login = this.login.bind(this);
  this.logout = this.logout.bind(this);
}

App.prototype.state = {
  authenticated: false,
  accessToken: false,
  currentRoute: '/',
  routes: {
    '/': {
      id: 'loading',
      onMount: function(page) {
        if (this.state.authenticated === true) {
          return this.redirectTo('/home');
        }
        return this.redirectTo('/login');
      }
    },
    '/login': {
      id: 'login',
      onMount: function(page) {
        if (this.state.authenticated === true) {
          return this.redirectTo('/home');
        }
        var loginButton = page.querySelector('.btn-login');
        loginButton.addEventListener('click', this.login);
      }
    },
    '/home': {
      id: 'profile',
      onMount: function(page) {
        if (this.state.authenticated === false) {
          return this.redirectTo('/login');
        }
        var logoutButton = page.querySelector('.btn-logout');
        var avatar = page.querySelector('#avatar');
        var profileCodeContainer = page.querySelector('.profile-json');
        logoutButton.addEventListener('click', this.logout);
        this.loadProfile(function(err, profile) {
          if (err) {
            profileCodeContainer.textContent = 'Error ' + err.message;
          }
          profileCodeContainer.textContent = JSON.stringify(profile, null, 4);
          avatar.src = profile.picture;
        });
      }
    }
  }
};

App.prototype.run = function(id) {
  this.container = getBySelector(id);
  this.resumeApp();
};

App.prototype.loadProfile = function(cb) {
  this.auth0.userInfo(this.state.accessToken, cb);
};

App.prototype.login = function(e) {
  e.target.disabled = true;

  var client = new Auth0Cordova({
    domain: 'YOUR_AUTH0_DOMAIN',
    clientId: 'YOUR_CLIENT_ID',
    packageIdentifier: 'YOUR_PACKAGE_ID' // found in config.xml
  });

  var options = {
    scope: 'openid profile',
    audience: 'https://YOUR_AUTH0_DOMAIN/userinfo'
  };
  var self = this;
  client.authorize(options, function(err, authResult) {
    if (err) {
      console.log(err);
      return (e.target.disabled = false);
    }
    localStorage.setItem('access_token', authResult.accessToken);
    self.resumeApp();
  });
};

App.prototype.logout = function(e) {
  localStorage.removeItem('access_token');
  this.resumeApp();
};

App.prototype.redirectTo = function(route) {
  if (!this.state.routes[route]) {
    throw new Error('Unknown route ' + route + '.');
  }
  this.state.currentRoute = route;
  this.render();
};

App.prototype.resumeApp = function() {
  var accessToken = localStorage.getItem('access_token');

  if (accessToken) {
    this.state.authenticated = true;
    this.state.accessToken = accessToken;
  } else {
    this.state.authenticated = false;
    this.state.accessToken = null;
  }

  this.render();
};

App.prototype.render = function() {
  var currRoute = this.state.routes[this.state.currentRoute];
  var currRouteEl = getById(currRoute.id);
  var element = document.importNode(currRouteEl.content, true);
  this.container.innerHTML = '';
  this.container.appendChild(element);
  currRoute.onMount.call(this, this.container);
};

module.exports = App;

Add Login and Logout Controls

Add controls to your app to allow users to log in and log out. The buttons should have classes which can be picked up with a querySelector and have event listeners attached to them as is demonstrated above.

<!-- www/index.html -->

<button class="btn btn-success btn-login">
  Log In
</button>

<button class="btn btn-success btn-logout">
  Log Out
</button>

After authentication, users will be redirected to your application where they will be taken to the profile route.

Troubleshooting

Cannot read property 'isAvailable' of undefined

This means that you're attempting to test this in a browser. At this time you'll need to run this either in an emulator or on a device.

Use Auth0 for FREECreate free Account