Skip to content

How to Sign In with Auth0 Using Capacitor

Auth0 is one of the most popular identity platforms, offering authentication and authorization as a service. If you're building a cross-platform app with Capacitor, the OAuth plugin makes it easy to integrate Auth0 using the Authorization Code flow with PKCE. This guide walks you through application setup, sign-in, token management, and fetching user profile information.

Prerequisites

Before you begin, make sure you have the following:

  • An Auth0 account. If you don't have one, you can sign up for free.
  • A Capacitor app with the OAuth plugin installed. To install the plugin, please refer to the Installation section in the plugin documentation.

Setting Up Auth0

Creating an Application

First, you need to create an application in the Auth0 Dashboard:

  1. Sign in to the Auth0 Dashboard.
  2. Navigate to Applications > Applications > Create Application.
  3. Enter a Name for your application (e.g. My Capacitor App).
  4. Select Native as the application type and click Create.
  5. On the Settings tab, note the Domain and Client ID. You will need these later.

Configuring Callback URLs

You need to configure a callback URL for each platform you want to support. In your application's Settings tab, add the following URLs to the Allowed Callback URLs field (comma-separated).

Android and iOS: Use a custom scheme based on your app's package name or bundle identifier:

com.example.app://oauth/callback

Web: Use your web app's URL:

http://localhost:3000/oauth/callback

Configuring Logout URLs

To support logout, you also need to add the following URLs to the Allowed Logout URLs field in your application's Settings tab.

Android and iOS:

com.example.app://oauth/logout

Web:

http://localhost:3000/oauth/logout

Implementing Authentication

Throughout the following examples, replace {domain} with your Auth0 Domain and {client-id} with your Client ID.

Signing In

Use the login(...) method to start the OAuth flow. The plugin automatically fetches the OpenID Connect discovery document from the issuer URL and handles the PKCE exchange:

import { Oauth } from '@capawesome-team/capacitor-oauth';

const login = async () => {
  const result = await Oauth.login({
    issuerUrl: 'https://{domain}',
    clientId: '{client-id}',
    redirectUrl: 'com.example.app://oauth/callback',
    scopes: ['openid', 'profile', 'email', 'offline_access'],
  });
  console.log('Access token:', result.accessToken);
  console.log('ID token:', result.idToken);
  console.log('Refresh token:', result.refreshToken);
};

Include the offline_access scope to receive a refresh token.

Handling the Redirect Callback (Web)

On the web, the login(...) method redirects the user to the Auth0 login page. After authentication, the user is redirected back to your app. You need to call handleRedirectCallback() on page load to complete the token exchange:

import { Oauth } from '@capawesome-team/capacitor-oauth';
import { Capacitor } from '@capacitor/core';

const handleRedirectCallback = async () => {
  if (Capacitor.getPlatform() !== 'web') {
    return;
  }
  const url = new URL(window.location.href);
  if (!url.searchParams.has('code')) {
    return;
  }
  const result = await Oauth.handleRedirectCallback();
  console.log('Access token:', result.accessToken);
};

handleRedirectCallback();

This step is only required on the web. On Android and iOS, the redirect is handled natively.

Refreshing the Access Token

Access tokens expire after a short time. Use the refreshToken(...) method to get a new access token without requiring the user to sign in again:

import { Oauth } from '@capawesome-team/capacitor-oauth';

const refreshToken = async () => {
  const result = await Oauth.refreshToken({
    issuerUrl: 'https://{domain}',
    clientId: '{client-id}',
    refreshToken: 'YOUR_REFRESH_TOKEN',
  });
  console.log('New access token:', result.accessToken);
};

Decoding the ID Token

Use the decodeIdToken(...) method to read the user's profile claims from the ID token:

import { Oauth } from '@capawesome-team/capacitor-oauth';

const decodeIdToken = async () => {
  const result = await Oauth.decodeIdToken({
    token: 'YOUR_ID_TOKEN',
  });
  console.log('Name:', result.payload.name);
  console.log('Email:', result.payload.email);
};

This decodes the JWT locally without sending it to a server. For server-side validation, you should verify the token on your backend.

Signing Out

End the session with the logout(...) method:

import { Oauth } from '@capawesome-team/capacitor-oauth';

const logout = async () => {
  await Oauth.logout({
    issuerUrl: 'https://{domain}',
    idToken: 'YOUR_ID_TOKEN',
    postLogoutRedirectUrl: 'com.example.app://oauth/logout',
  });
};

Fetching the User Profile

To fetch the authenticated user's profile from Auth0, you can call the /userinfo endpoint using the access token:

import { Oauth } from '@capawesome-team/capacitor-oauth';

const login = async () => {
  const result = await Oauth.login({
    issuerUrl: 'https://{domain}',
    clientId: '{client-id}',
    redirectUrl: 'com.example.app://oauth/callback',
    scopes: ['openid', 'profile', 'email', 'offline_access'],
  });

  const response = await fetch('https://{domain}/userinfo', {
    headers: {
      Authorization: `Bearer ${result.accessToken}`,
    },
  });
  const user = await response.json();
  console.log('Name:', user.name);
  console.log('Email:', user.email);
};

Conclusion

In this guide, we covered how to set up Auth0 authentication in a Capacitor app using the OAuth plugin. From application setup and callback configuration to sign-in, token refresh, and fetching the user profile, the plugin handles the complexity of the OAuth flow so you can focus on building your application.

Explore the complete API Reference to see all available methods and options. Have suggestions or questions? Create an issue in our GitHub repository.

Stay connected with us on X and subscribe to our newsletter for the latest updates.