Ionic & Capacitor (Vue)

View on Github

Ionic & Capacitor (Vue)

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

This tutorial demonstrates how to add user login with Auth0 to an Ionic Vue & 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://{yourDomain}/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://{yourDomain}/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 Vue SDK

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

npm install @auth0/auth0-vue

Was this helpful?

/

The SDK exposes several types that help you integrate Auth0 with your Vue 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 you to interact with the device's system browser and is used to open the URL to Auth0's authorizaction endpoint
  • @capacitor/app - allows you to subscribe to high-level app events, useful for handling callbacks from Auth0

Configure the createAuth0 plugin

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

Open src/main.ts and install the plugin using app.use

import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";

import { IonicVue } from "@ionic/vue";

import { createAuth0 } from "@auth0/auth0-vue";
import config from "./auth.config";

// ..

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

const app = createApp(App).use(IonicVue).use(router);

app.use(
  createAuth0({
    domain: "{yourDomain}",
    clientId: "{yourClientId}",
    useRefreshTokens: true,
    useRefreshTokensFallback: false,
    authorizationParams: {
      redirect_uri
    }
  })
);

router.isReady().then(() => {
  app.mount("#app");
});

Was this helpful?

/

The createAuth0 plugin takes the following props:

  • 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
  • useRefreshTokens: To use auth0-vue with Ionic on Android and iOS, it's required to enable refresh tokens.
  • useRefreshTokensFallback: To use auth0-vue with Ionic on Android and iOS, it's required to disable the iframe fallback.
  • authorizationParams.redirect_uri: The URL to where you'd like to redirect your users after they authenticate with Auth0.

Checkpoint

Now that you have configured createAuth0 plugin, run your application to verify that the SDK is initializing correctly, and your application is not throwing any errors related to Auth0.

Add Login to Your Application

In a Capacitor application, the Capacitor's Browser plugin performs a redirect to the Auth0 Universal Login Page. Set the openUrl parameter on the loginWithRedirect function to use Browser.open so that the URL is opened using the device's system browser component (SFSafariViewController on iOS, and Chrome Custom Tabs on Android).

Add a new file LoginButton.vue with the following code:

<template>
  <ion-button @click="login">Log in</ion-button>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import { IonApp, IonRouterOutlet } from "@ionic/vue";

import { useAuth0 } from "@auth0/auth0-vue";
import { App as CapApp } from "@capacitor/app";
import { Browser } from "@capacitor/browser";

export default defineComponent({
  components: {
    IonButton,
  },
  setup() {
    const { loginWithRedirect } = useAuth0();

    const login = async () => {
      await loginWithRedirect({
        openUrl: (url: string) =>
          Browser.open({
            url,
            windowName: "_self",
          }),
      });
    };

    return { login };
  },
});
</script>

Was this helpful?

/

This component:

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

Handling the callback

Once users logs in with the Universal Login Page, they redirect back to your app via a URL with a custom URL scheme. The appUrlOpen event must be handled within your app. You can call the handleRedirectCallback method from the Auth0 SDK to initialize the authentication state.

You can only use this method on a redirect from Auth0. To verify success, check for the presence of the code and state parameters in the URL.

The Browser.close() method should close the browser when this event is raised.

Add the following capacitor application listener to your main App component:

<template>
  <ion-app>
    <ion-router-outlet />
  </ion-app>
</template>

<script lang="ts">
import { useAuth0 } from "@auth0/auth0-vue";
import { IonApp, IonRouterOutlet } from "@ionic/vue";
import { defineComponent } from "vue";
import { App as CapApp } from "@capacitor/app";
import { Browser } from "@capacitor/browser";

export default defineComponent({
  name: "App",
  components: {
    IonApp,
    IonRouterOutlet,
  },
  setup() {
    const { handleRedirectCallback } = useAuth0();

    // Handle the 'appUrlOpen' event and call `handleRedirectCallback`
    CapApp.addListener('appUrlOpen', async ({ url }) => {
      if (url.includes('state') && (url.includes('code') || url.includes('error'))) {
        await handleRedirectCallback(url);
      }
      // No-op on Android
      await Browser.close();
    });
  },
});
</script>

Was this helpful?

/

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 users can log in, you need to configure a way to log out. Users must redirect to the Auth0 logout endpoint in the browser to clear their browser session. Again, Capacitor's Browser plugin should perform this redirect so that the user does not leave your app and receive a suboptimal experience.

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

  • Construct the URL for your app Auth0 should use to redirect to after logout. This is a URL that uses your registered custom scheme and Auth0 domain. Add it to your Allowed Logout URLs configuration in the Auth0 Dashboard
  • Logout from the SDK by calling logout, and pass your redirect URL back as the logoutParams.returnTo parameter.
  • Set the openUrl parameter to a callback that uses the Capacitor browser plugin to open the URL using Browser.open.

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

<template>
  <ion-button @click="onLogout">Log out</ion-button>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import { useAuth0 } from "@auth0/auth0-vue";
import { Browser } from "@capacitor/browser";
import { IonButton } from "@ionic/vue";
import { callbackUri } from "../auth.config";

export default defineComponent({
  components: {
    IonButton,
  },
  setup() {
    const { logout } = useAuth0();

    const onLogout = async () => {
      await logout({
        logoutParams: {
          returnTo: callbackUri,
        },
        openUrl: (url: string) =>
          Browser.open({
            url,
            windowName: "_self",
          }),
      });
    };

    return {
      onLogout,
    };
  },
});
</script>

Was this helpful?

/

Checkpoint

Add the LogoutButton component to your application. When you click it, verify that your Ionic application redirects you 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 Vue 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 the useAuth0() composable. Take this UserProfile component as an example of how to use it:

<template>
  <div v-if="isLoading">Loading ...</div>
  <div v-else-if="!user"></div>
  <div v-else class="profile-container">
    <ion-avatar>
      <img :src="user.picture" :alt="user.name" />
    </ion-avatar>
    <h2>{{ user.name }}</h2>
    <p>{{ user.email }}</p>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import { useAuth0 } from "@auth0/auth0-vue";
import { IonAvatar } from "@ionic/vue";

export default defineComponent({
  components: {
    IonAvatar,
  },
  setup() {
    const { user, isLoading } = useAuth0();

    return { user, isLoading };
  },
});
</script>

Was this helpful?

/

The user property contains sensitive information and artifacts related to the user's identity. As such, its availability depends on the user's authentication status. To prevent any render errors, use the isAuthenticated property from useAuth0() to check if Auth0 has authenticated the user before Vue renders any component that consumes the user property. Ensure that the SDK has completed loading before accessing the isAuthenticated property, by checking that isLoading is false.

Checkpoint

Add the UserProfile component 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