Cordova

View on Github

Cordova

Gravatar for david.patrick@auth0.com
By David Patrick

This tutorial demonstrates how to add user login to an Cordova application using Auth0. We recommend that you log in to follow this quickstart with examples configured for your account.

I want to explore a sample app

2 minutes

Get a sample configured with your account settings or check it out on Github.

View on Github
System requirements: NodeJS 10 | Cordova 9

Configure Auth0

Get Your Application Keys

When you signed up for Auth0, a new application was created for you, or you could have created a new one. You will need some details about that application to communicate with Auth0. You can get these details from the Application Settings section in the Auth0 dashboard.

App Dashboard

You need the following information:

  • Domain
  • Client ID

Configure Callback URLs

A callback URL is a URL in your application where Auth0 redirects the user after they have authenticated. The callback URL for your app must be added to the Allowed Callback URLs field in your Application Settings. If this field is not set, users will be unable to log in to the application and will get an error.

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://{yourDomain}/cordova/YOUR_PACKAGE_ID/callback

Was this helpful?

/

Configure Logout URLs

A logout URL is a URL in your application that Auth0 can return to after the user has been logged out of the authorization server. This is specified in the returnTo query parameter. The logout URL for your app must be added to the Allowed Logout URLs field in your Application Settings. If this field is not set, users will be unable to log out from the application and will get an error.

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

file://*

Was this helpful?

/

Lastly, be sure that the Application Type for your application is set to Native in its 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

Was this helpful?

/

Add Cordova Plugins

You must install the SafariViewController plugin from Cordova to be able to show the 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

Was this helpful?

/

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={yourDomain} --variable ANDROID_PATHPREFIX=/cordova/{YOUR_PACKAGE_ID}/callback

Was this helpful?

/

Integrate Auth0 in your Application

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.

// src/index.js

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);

Was this helpful?

/

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.

// src/App.js

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

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

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

function getRedirectUrl() {
  var returnTo = env.PACKAGE_ID + '://{yourDomain}/cordova/' + env.PACKAGE_ID + '/callback';
  var url = 'https://{yourDomain}/v2/logout?client_id={yourClientId}&returnTo=' + returnTo;
  return url;
}

function openUrl(url) {
  SafariViewController.isAvailable(function (available) {
    if (available) {
      SafariViewController.show({
            url: url
          },
          function(result) {
            if (result.event === 'loaded') {
              SafariViewController.hide();
            }
          },
          function(msg) {
            console.log("KO: " + JSON.stringify(msg));
          })
    } else {
      window.open(url, '_system');
    }
  })
}

function App() {
  this.auth0 = new Auth0.Authentication({
    domain: '{yourDomain}',
    clientID: '{yourClientId}'
  });
  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: '{yourDomain}',
    clientId: '{yourClientId}',
    packageIdentifier: 'YOUR_PACKAGE_ID' // found in config.xml
  });

  var options = {
    scope: 'openid profile',
    audience: 'https://{yourDomain}/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');
  var url = getRedirectUrl();
  openUrl(url);
  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;

Was this helpful?

/

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>

Was this helpful?

/

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 FREE