Ionic & Capacitor (Angular)

View on Github

Ionic & Capacitor (Angular)

Gravatar for steve.hobbs@auth0.com
By Steve Hobbs

This tutorial demonstrates how to add user login with Auth0 to an Ionic Angular & Capacitor application. 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: Node & Npm (LTS) | XCode 12+ (for iOS) | Android Studio 4+ (for Android)

Getting started

This quickstart assumes you already have an Ionic application up and running with Capacitor. If not, check out the Using Capacitor with Ionic Framework guide to get started with a simple app, or clone our sample apps.

You should also be familiar with the Capacitor development workflow.

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.

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

You should set the Allowed Callback URL to:

YOUR_PACKAGE_ID://YOUR_DOMAIN/capacitor/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.

You should set the Allowed Logout URLs to

YOUR_PACKAGE_ID://YOUR_DOMAIN/capacitor/YOUR_PACKAGE_ID/callback

Was this helpful?

/

Configure Origins

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

capacitor://localhost, http://localhost

Was this helpful?

/

These origins are required for iOS and Android respectively.

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

Install the Auth0 Angular SDK

Run the following command within your project directory to install the Auth0 Angular SDK:

npm install @auth0/auth0-angular

Was this helpful?

/

The SDK exposes several types that help you integrate Auth0 with your Angular application idiomatically, including a module and an authentication service.

Install Capacitor plugins

This quickstart and sample make use of some of Capacitor's official plugins. Install these into your app using the following command:

npm install @capacitor/browser @capacitor/app

Was this helpful?

/
  • @capacitor/browser - allows us to interact with the device's system browser, and is used to open the URL to Auth0's authorizaction endpoint
  • @capacitor/app - allows us to subscribe to high-level app events, useful for handling callbacks from Auth0

Configure your App module

The SDK exports AuthModule, a module that contains all the services required for the SDK to function. To register this with your application:

  • Open the app.module.ts file
  • Import the AuthModule type from the @auth0/auth0-angular package
  • Add AuthModule to the application by calling AuthModule.forRoot and adding to your application module's imports array
  • Specify the configuration for the Auth0 Angular SDK
// Import the types from the SDK
import { AuthModule } from '@auth0/auth0-angular';
import config from '../../capacitor.config';

// ..

// Build the URL that Auth0 should redirect back to
const redirectUri = `${config.appId}://YOUR_DOMAIN/capacitor/${config.appId}/callback`;

// Register AuthModule with your AppModule
@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [
    BrowserModule,
    IonicModule.forRoot(),
    AppRoutingModule,
    AuthModule.forRoot({
      domain: "YOUR_DOMAIN",
      clientId: "YOUR_CLIENT_ID",
      redirectUri
    }),
  ],
  providers: [{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }],
  bootstrap: [AppComponent],
})

Was this helpful?

/

The AuthModule.forRoot function takes the following configuration:

  • domain: The "domain" value present under the "Settings" of the application you created in your Auth0 dashboard, or your custom domain if using Auth0's Custom Domains feature
  • clientId: The "client ID" value present under the "Settings" of the application you created in your Auth0 dashboard
  • redirectUri: The URL to where you'd like to redirect your users after they authenticate with Auth0.

Checkpoint

Now that you have configured your app with the Auth0 Angular SDK, run your application to verify that the SDK is initializing without error and that your application runs as it did before.

Add Login to Your Application

In a Capacitor application, the Capacitor's Browser plugin should be used to perform a redirect to the Auth0 Universal Login Page. Use the buildAuthorizeUrl function to get the URL to redirect the user.

Add a new LoginButton component to your application with the following code:

import { Component, OnInit } from '@angular/core';
import { AuthService } from '@auth0/auth0-angular';
import { Browser } from '@capacitor/browser';
import { mergeMap } from 'rxjs/operators';

@Component({
  selector: 'app-login-button',
  template: `<ion-button (click)="login()">Login</ion-button>`,
})
export class LoginButtonComponent {
  constructor(public auth: AuthService) {}

  login() {
    this.auth
      .buildAuthorizeUrl()
      .pipe(mergeMap((url) => Browser.open({ url, windowName: '_self' })))
      .subscribe();
  }
}

Was this helpful?

/

This component:

  • defines a template with a simple button that logs the user in when clicked
  • uses buildAuthorizeUrl to construct a URL to Auth0's Universal Login page
  • uses Capacitor's Browser plugin to open the URL and show the login page to the user

Handling the callback

Once a user has logged in using the Universal Login Page, they will be redirected back to your app using a URL with a custom URL scheme. The appUrlOpen event must be handled within your app, where handleRedirectCallback can be called to initialize the authentication state within the SDK.

Modify your App component and use the ngOnInit method to handle the callback from Auth0.

import { Component, OnInit, NgZone } from '@angular/core';
import { AuthService } from '@auth0/auth0-angular';
import { mergeMap } from 'rxjs/operators';
import { Browser } from '@capacitor/browser';
import { App } from '@capacitor/app';

const callbackUri = `${config.appId}://YOUR_DOMAIN/capacitor/${config.appId}/callback`;

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.scss'],
})
export class AppComponent implements OnInit {
  // Import the AuthService module from the Auth0 Angular SDK
  constructor(public auth: AuthService, private ngZone: NgZone) {}

  ngOnInit(): void {
    // Use Capacitor's App plugin to subscribe to the `appUrlOpen` event
    App.addListener('appUrlOpen', ({ url }) => {
      // Must run inside an NgZone for Angular to pick up the changes
      // https://capacitorjs.com/docs/guides/angular
      ngZone.run(() => {
        if (url?.startsWith(callbackUri)) {
          // If the URL is an authentication callback URL..
          if (
            url.includes('state=') &&
            (url.includes('error=') || url.includes('code='))
          ) {
            // Call handleRedirectCallback and close the browser
            this.auth
              .handleRedirectCallback(url)
              .pipe(mergeMap(() => Browser.close()))
              .subscribe();
          } else {
            Browser.close();
          }
        }
      });
    });
  }
}

Was this helpful?

/

Note that the appUrlOpen event callback is wrapped in ngZone.run, which means that the changes to observables that occur when handleRedirectCallback runs are picked up by the Angular app. Please read Using Angular with Capacitor for more details. Otherwise, the screen will not update to show the authenticated state after you log in.

Checkpoint

Add the LoginButton component to your application, as well as the handler for the "appUrlOpen" event to your App component. When you click the login button, verify that your application redirects you to the Auth0 Universal Login Page and that you can now log in or sign up using a username and password or a social provider.

Once that's complete, verify that Auth0 redirects you back to your application.

Add Logout to Your Application

Now that you can log in, you need a way to log out. To do this, the user must be redirected to the Auth0 logout endpoint in the browser in order to clear their browser session. Again, Capacitor's Browser plugin should be used to perform this redirect so that the user does not leave your app and otherwise receive a suboptimal experience.

To achieve this with Ionic and Capacitor in conjunction with the Auth0 SDK, the steps are:

  • Use the SDK to build the URL to the logout endpoint by calling buildLogoutUrl
  • Call the logout function on the SDK, setting localOnly: true. This will clear the internal state of the SDK but not perform the redirect to Auth0
  • Redirect the user to the logout endpoint using Browser.open

Create a new LogoutButton component and add the following code to the file. Then, add the LogoutButton component to your app.

import { Component, OnInit } from '@angular/core';
import { AuthService } from '@auth0/auth0-angular';
import { Browser } from '@capacitor/browser';
import { tap } from 'rxjs/operators';

// Build the URL to return back to your app after logout
const returnTo = `${config.appId}://YOUR_DOMAIN/capacitor/${config.appId}/callback`;

@Component({
  selector: 'app-logout-button',
  template: `<ion-button (click)="logout()">Log out</ion-button>`,
})
export class LogoutButtonComponent {
  // Import the AuthService module from the Auth0 Angular SDK
  constructor(public auth: AuthService) {}

   logout() {
    // Use the SDK to build the logout URL
    this.auth
      .buildLogoutUrl({ returnTo })
      .pipe(
        tap((url) => {
          // Call the logout fuction, but only log out locally
          this.auth.logout({ localOnly: true });
          // Redirect to Auth0 using the Browser plugin, to clear the user's session
          Browser.open({ url });
        })
      )
      .subscribe();
  }
}

Was this helpful?

/

Checkpoint

Add the LogoutButton component to your application. When you click it, verify that your Ionic application redirects you to the address you specified as one of the "Allowed Logout URLs" in the "Settings" and that you are no longer logged in to your application.

Show User Profile Information

The Auth0 SDK helps you retrieve the profile information associated with logged-in users quickly in whatever component you need, such as their name or profile picture, to personalize the user interface. The profile information is available through the user$ property exposed by AuthService.

Create a new component Profile, and use the following code to display user profile information in your app.

import { Component, OnInit } from '@angular/core';
import { AuthService } from '@auth0/auth0-angular';

@Component({
  selector: 'app-profile',
  template: `
  <div *ngIf="auth.user$ | async as user">
    <ion-avatar class="avatar">
      <img [src]="user.picture" [alt]="user.name" />
    </ion-avatar>
    <h2>{{ user.name }}</h2>
    <p>{{ user.email }}</p>
  </div>`,
})
export class ProfileComponent {
  constructor(public auth: AuthService) {}
}

Was this helpful?

/

Checkpoint

Add ProfileComponent to your application, and verify that you can display the user.name or any other user property within a component correctly after you have logged in.

Use Auth0 for FREE