Skip to content

How to Sign In with Azure Entra ID Using Capacitor

Many enterprise applications rely on Microsoft Entra ID (formerly Azure Active Directory) for identity and access management. If you're building a cross-platform app with Capacitor, the OAuth plugin makes it straightforward to integrate Entra ID authentication using the Authorization Code flow with PKCE. This guide walks you through app registration, sign-in, token management, and accessing the Microsoft Graph API.

Prerequisites

Before you begin, make sure you have the following:

  • A Microsoft Entra ID tenant. If you don't have one, you can create a free Azure account.
  • A Capacitor app with the OAuth plugin installed. To install the plugin, please refer to the Installation section in the plugin documentation.

Setting Up Azure Entra ID

Registering Your App

First, you need to register your application in the Microsoft Entra admin center:

  1. Sign in to the Microsoft Entra admin center.
  2. Navigate to Entra ID > App registrations > New registration.
  3. Enter a Name for your application (e.g. My Capacitor App).
  4. Under Supported account types, select the option that fits your use case:
    • Single tenant: Only accounts in your directory.
    • Multitenant: Accounts in any organizational directory.
    • Multitenant + personal: Includes Microsoft personal accounts.
  5. Under Redirect URI, select the platform and enter a redirect URI (see Configuring Redirect URIs below).
  6. Click Register.
  7. On the app overview page, note the Application (client) ID and Directory (tenant) ID. You will need these later.

Configuring Redirect URIs

You need to register a redirect URI for each platform you want to support. To add multiple redirect URIs, go to Overview > Redirect URIs and click Add Redirect URI.

Android and iOS: Select Public client/native (mobile & desktop) and use a custom scheme based on your app's package name or bundle identifier:

com.example.app://oauth/callback

Web: Select Single-page application (SPA) and use your web app's URL:

http://localhost:3000/oauth/callback

Implementing Authentication

Throughout the following examples, replace {tenant-id} with your Directory (tenant) ID and {client-id} with your Application (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://login.microsoftonline.com/{tenant-id}/v2.0',
    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 Microsoft 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://login.microsoftonline.com/{tenant-id}/v2.0',
    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.preferred_username);
};

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://login.microsoftonline.com/{tenant-id}/v2.0',
    idToken: 'YOUR_ID_TOKEN',
    postLogoutRedirectUrl: 'com.example.app://oauth/logout',
  });
};

Note that Microsoft Entra ID may show a "You have signed out" page instead of redirecting back to your app. In this case, the user needs to close the browser manually, which results in a USER_CANCELED error even though the logout was successful.

Accessing the Microsoft Graph API

To call the Microsoft Graph API, request the User.Read scope (or other scopes you need) during login and use the access token in your requests:

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

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

  const response = await fetch('https://graph.microsoft.com/v1.0/me', {
    headers: {
      Authorization: `Bearer ${result.accessToken}`,
    },
  });
  const user = await response.json();
  console.log('Display name:', user.displayName);
  console.log('Email:', user.mail);
};

Conclusion

In this guide, we covered how to set up Microsoft Entra ID authentication in a Capacitor app using the OAuth plugin. From app registration and redirect URI configuration to sign-in, token refresh, and Microsoft Graph API access, 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.