Ionic 3

View on Github

Ionic 3

Gravatar for
By David Patrick

This tutorial demonstrates how to add user login to an Ionic 3 application using Auth0. We recommend you to 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: Ionic 3.x | Angular 5+ | Nodejs 10.17.x

New to Auth? Learn How Auth0 works, how it integrates with Native Applications and which protocol it uses.

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.

You need the following information:

  • Domain
  • Client ID

If you download the sample from the top of this page these details are filled out for you.

If you have more than one application 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.

The callback URL for your app must be whitelisted in 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.

If you are following along with the sample project you downloaded from the top of this page, you should set the Allowed Callback URL to

# replace YOUR_PACKAGE_ID with your app package ID

Replace YOUR_PACKAGE_ID with your application's package name, available as the applicationId attribute in the app/build.gradle file.

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 whitelisted in 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.

If you are following along with the sample project you downloaded from the top of this page, you should set the Allowed Logout URL to

# replace YOUR_PACKAGE_ID with your app package ID

To be able to make requests from your application to Auth0, set the following origins in your Application Settings.

http://localhost, ionic://localhost, http://localhost:8100

The origins http://localhost and ionic://localhost are needed for Android and iOS. respectively The origin http://localhost:8100 is needed when you are running the application with livereaload activated.

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

Install the Dependencies

The required dependencies for using Auth0 in an Ionic 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 use universal login. The downloadable sample project already has this plugin added, but if you are embedding Auth0 in your own application, install the plugin via the command line.

ionic cordova plugin add cordova-plugin-safariviewcontroller

# installation with npm
npm install --save @ionic-native/safari-view-controller

# installation with yarn
yarn add @ionic-native/safari-view-controller

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
ionic cordova plugin add cordova-plugin-customurlscheme --variable URL_SCHEME=YOUR_PACKAGE_ID --variable ANDROID_SCHEME=YOUR_PACKAGE_ID --variable ANDROID_HOST=YOUR_DOMAIN --variable ANDROID_PATHPREFIX=/cordova/YOUR_PACKAGE_ID/callback

Replace YOUR_PACKAGE_ID with your application's package name, available as the applicationId attribute in the app/build.gradle file.

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/app/app.component.ts

import { Component } from '@angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

import { TabsPage } from '../pages/tabs/tabs';

// Import Auth0Cordova
import Auth0Cordova from '@auth0/cordova';

  templateUrl: 'app.html'
export class MyApp {
  rootPage:any = TabsPage;

    platform: Platform,
    statusBar: StatusBar,
    splashScreen: SplashScreen
  ) {
    platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.

      // Redirect back to app after authenticating
      (window as any).handleOpenURL = (url: string) => {

Configure Auth0

Create a new file called auth.config.ts in your src/services folder to provide the necessary Auth0 configuration for your Ionic app:

// src/services/auth.config.ts

export const AUTH_CONFIG = {
  // Needed for Auth0 (capitalization: ID):
  clientID: 'YOUR_CLIENT_ID',
  // Needed for Auth0Cordova (capitalization: Id):
  clientId: 'YOUR_CLIENT_ID',
  domain: 'YOUR_DOMAIN',
  packageIdentifier: 'YOUR_PACKAGE_ID' // config.xml widget ID, e.g., com.auth0.ionic

Be sure to replace YOUR_PACKAGE_ID with the identifier for your app.

Create an Authentication Service

To coordinate authentication tasks, it's best to set up an injectable service that can be reused across the application. This service needs methods for logging users in and out, as well as checking their authentication state.

// src/services/auth.service.ts
import { Injectable, NgZone } from '@angular/core';
import { Storage } from '@ionic/storage';
import { SafariViewController } from '@ionic-native/safari-view-controller';

// Import AUTH_CONFIG, Auth0Cordova, and auth0.js
import { AUTH_CONFIG } from './auth.config';
import Auth0Cordova from '@auth0/cordova';
import * as auth0 from 'auth0-js';

export class AuthService {
  Auth0 = new auth0.WebAuth(AUTH_CONFIG);
  Client = new Auth0Cordova(AUTH_CONFIG);
  accessToken: string;
  user: any;
  loggedIn: boolean;
  loading = true;

    public zone: NgZone,
    private storage: Storage,
    private safariViewController: SafariViewController
  ) {'profile').then(user => this.user = user);'access_token').then(token => this.accessToken = token);'expires_at').then(exp => {
      this.loggedIn = < JSON.parse(exp);
      this.loading = false;

  login() {
    this.loading = true;
    const options = {
      scope: 'openid profile offline_access'
    // Authorize login request with Auth0: open login page and get auth results
    this.Client.authorize(options, (err, authResult) => {
      if (err) { => this.loading = false);
        throw err;
      // Set Access Token'access_token', authResult.accessToken);
      this.accessToken = authResult.accessToken;
      // Set Access Token expiration
      const expiresAt = JSON.stringify((authResult.expiresIn * 1000) + new Date().getTime());'expires_at', expiresAt);
      // Set logged in
      this.loading = false;
      this.loggedIn = true;
      // Fetch user's profile info
      this.Auth0.client.userInfo(this.accessToken, (err, profile) => {
        if (err) {
          throw err;
        }'profile', profile).then(val =>
 => this.user = profile)

  logout() {'profile');'access_token');'expires_at');
    this.accessToken = null;
    this.user = null;
    this.loggedIn = false;

      .then((available: boolean) => {
let url = `https://${AUTH_CONFIG.domain}/v2/logout?client_id=${AUTH_CONFIG.clientId}&returnTo=${AUTH_CONFIG.packageIdentifier}://${AUTH_CONFIG.domain}/cordova/${AUTH_CONFIG.packageIdentifier}/callback`;
        if (available) {
            url: url
          .subscribe((result: any) => {
              if(result.event === 'opened') console.log('Opened');
              else if(result.event === 'loaded') console.log('Loaded');
              else if(result.event === 'closed') console.log('Closed');
            (error: any) => console.error(error)
        } else {
          // use fallback browser
, '_system');

Add Authentication with Auth0

Add a control to your app to allow users to log in. The control should call the login method from the AuthService. Start by injecting the AuthService in a component.

// src/pages/home/home.ts
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { AuthService } from './../../services/auth.service';

  selector: 'page-home',
  templateUrl: 'home.html'
export class HomePage {

    public navCtrl: NavController,
    public auth: AuthService
  ) {}


The AuthService is now accessible in the view and its login method can be called.

<!-- src/pages/home/home.html -->


<ion-content padding>
  <p *ngIf="auth.loading" text-center>Loading...</p>
  <ng-template [ngIf]="!auth.loading">
    <!-- Not loading, not logged in: show login button -->
      (click)="auth.login()">Log In</button>
    <!-- Not loading, logged in: show profile and logout button -->
    <ng-template [ngIf]="auth.loggedIn">
      <ion-card *ngIf="auth.user">
        <img [src]="auth.user.picture">
          <ion-card-title>{{ }}</ion-card-title>
          <pre>{{ auth.user | json }}</pre>
        (click)="auth.logout()">Log Out</button>

Add Platform and Run the App

You will now need to allow Ionic / Cordova to install the necessary plugins and update your config.xml appropriately for the platform you wish to run on.

Use the following commands to add your desired platform(s) (e.g., ios or android) and run the app:

# Add platform (e.g., ios or android)
$ ionic cordova platform add {platform}
# Run on desired platform (e.g., ios or android)
$ ionic cordova run {platform} --livereload

This will then launch your app in the local emulation environment for the platform you chose (Xcode Simulator for iOS or the Android emulator of your choice).

Don't be alarmed if you cannot authenticate successfully yet at this stage! There was some configuration generated by running the app that you still need to add to your Auth0 settings.

Update Auth0 Dashboard Configuration

  1. After executing the run command, your config.xml file should contain <allow-navigation> tag(s).
  2. Make note of IP address URLs from any <allow-navigation> tags.
  3. In your Auth0 Dashboard, go to your Ionic app's Settings.
  4. Add the full allowed navigation addresses (including http:// and ports) to the Allowed Origins (CORS) settings for your Auth0 application and click the Save Changes button.

You should now be able to log into your app!


Cannot read property 'isAvailable' of undefined

This means that you're attempting to test this in a browser. This library was designed to be run on a device and expects a Cordova environment with the SafariViewController plugin available.

Completely blank page when launching the app

This could either mean that you've built the seed project using a different version of Ionic, or that the device where you are testing it isn't entirely supported by Ionic 3 yet.

This could also occur on iOS if you are running the app in a simulator and something else is listening on port 8080 on the same machine. A good way to check for this is to run the application from XCode instead and check the logs.

Profile doesn't show after successful login

This is not actually an issue with your code, but is an Ionic quirk when running in an emulator (generally iOS). You can use a real device, or generally fix this by turning on live reload when you run your app in the emulator, and adding an alert in your auth.service.ts that simply creates a notification with the JSON stringified contents of the authResult in the Client.authorize() callback. This will generally fix the issue, and then you can remove the alert and everything should work normally.

Use Auth0 for FREE