npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

react-native-msal2

v1.0.18

Published

MSAL React Native wrapper for iOS and Android

Downloads

508

Readme

react-native-msal2

npm latest version semantic-release

A React Native wrapper around Microsoft Authentication Library (MSAL) for iOS and Android. Enables authentication with Microsoft identity platform (Azure AD, Azure AD B2C, Microsoft personal accounts) in your React Native apps.

Table of Contents

Features

  • Interactive and silent token acquisition
  • Azure AD and Azure AD B2C support
  • Multiple account management
  • Customizable webview parameters (iOS)
  • Android Custom Tabs browser configuration
  • TypeScript support out of the box

Prerequisites

  • React Native >= 0.70
  • iOS >= 12.0
  • Android minSdkVersion >= 21
  • An app registered in the Azure Portal

Installation

npm install react-native-msal2

iOS

cd ios && pod install

Android

No additional install steps required — autolinking handles it.

Platform Setup

iOS Setup

1. Register a Redirect URI

In the Azure Portal, add a redirect URI for iOS:

msauth.<your.bundle.id>://auth

2. Configure URL Scheme

Add the following to your Info.plist:

<key>CFBundleURLTypes</key>
<array>
  <dict>
    <key>CFBundleURLSchemes</key>
    <array>
      <string>msauth.$(PRODUCT_BUNDLE_IDENTIFIER)</string>
    </array>
  </dict>
</array>

3. Handle Auth Redirects

In your AppDelegate.m (or AppDelegate.mm), add:

#import <MSAL/MSAL.h>

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
{
  return [MSALPublicClientApplication handleMSALResponse:url sourceApplication:options[UIApplicationOpenURLOptionsSourceApplicationKey]];
}

4. Keychain Sharing (Optional)

If you need keychain sharing, add the Keychain Sharing capability in Xcode and add your bundle identifier as a keychain group.

Android Setup

1. Register a Redirect URI

The library automatically generates a redirect URI in the format:

msauth://<your.package.name>/<base64-encoded-signature-hash>

You can also provide a custom redirectUri in the config. Register whichever URI you use in the Azure Portal.

2. Configure BrowserTabActivity

Add the following activity to your AndroidManifest.xml inside the <application> tag:

<activity android:name="com.microsoft.identity.client.BrowserTabActivity">
  <intent-filter>
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" />
    <data
      android:scheme="msauth"
      android:host="<your.package.name>"
      android:path="/<url-encoded-signature-hash>" />
  </intent-filter>
</activity>

3. Get Your Signature Hash

To find your signature hash for the redirect URI:

keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64

Default debug keystore password is android.

Usage

Configuration

import PublicClientApplication from 'react-native-msal2';
import type { MSALConfiguration } from 'react-native-msal2';
import { Platform } from 'react-native';

const config: MSALConfiguration = {
  auth: {
    clientId: '<your-client-id>',
    // Defaults to 'https://login.microsoftonline.com/common'
    authority: 'https://login.microsoftonline.com/<tenant-id>',
    knownAuthorities: ['https://login.microsoftonline.com/<tenant-id>'],
    redirectUri: Platform.select({
      ios: 'msauth.<your.bundle.id>://auth',
      android: 'msauth://<your.package.name>/<signature-hash>',
    }),
  },
  // Android-specific options (optional)
  androidConfigOptions: {
    authorization_user_agent: 'DEFAULT',
    broker_redirect_uri_registered: false,
    logging: {
      pii_enabled: false,
      log_level: 'ERROR',
      logcat_enabled: true,
    },
  },
};

Initialization

You must call init() before using any other method:

const pca = new PublicClientApplication(config);

try {
  await pca.init();
} catch (error) {
  console.error('Error initializing MSAL:', error);
}

Acquire Token Interactively

Use this for the first-time login or when a silent token acquisition fails:

import type { MSALInteractiveParams, MSALResult } from 'react-native-msal2';

const params: MSALInteractiveParams = {
  scopes: ['User.Read'],
  promptType: MSALPromptType.SELECT_ACCOUNT,
  loginHint: '<email>',
};

const result: MSALResult | undefined = await pca.acquireToken(params);
console.log('Access token:', result?.accessToken);

Acquire Token Silently

Use this for subsequent token acquisitions using a cached account:

import type { MSALSilentParams } from 'react-native-msal2';

const params: MSALSilentParams = {
  scopes: ['User.Read'],
  account: result!.account,
  forceRefresh: false,
};

const silentResult = await pca.acquireTokenSilent(params);

Get Accounts

// Get all accounts with cached refresh tokens
const accounts = await pca.getAccounts();

// Get a specific account by identifier
const account = await pca.getAccount(accountIdentifier);

Remove Account / Sign Out

// Remove account from cache (works on both platforms)
await pca.removeAccount(account);

// Sign out with browser session cleanup (iOS only — falls back to removeAccount on Android)
import type { MSALSignoutParams } from 'react-native-msal2';

await pca.signOut({
  account,
  signoutFromBrowser: true,
});

API Reference

PublicClientApplication

| Method | Returns | Description | |---|---|---| | init() | Promise<this> | Initializes the native MSAL client. Must be called first. | | acquireToken(params) | Promise<MSALResult \| undefined> | Acquires a token interactively via a webview/browser. | | acquireTokenSilent(params) | Promise<MSALResult \| undefined> | Acquires a token silently from cache or by refreshing. | | getAccounts() | Promise<MSALAccount[]> | Returns all accounts with cached refresh tokens. | | getAccount(identifier) | Promise<MSALAccount \| undefined> | Returns the account matching the given identifier. | | removeAccount(account) | Promise<boolean> | Removes all cached tokens for the given account. | | signOut(params) | Promise<boolean> | Removes cached tokens and optionally signs out from the browser (iOS). | | getSelectedBrowser() | Promise<string> | Returns the browser used for auth. Android only (returns 'N/A' on iOS). | | getSafeCustomTabsBrowsers() | Promise<MSALAndroidPreferredBrowser[]> | Returns installed browsers supporting Custom Tabs. Android only. |

Types

MSALConfiguration

interface MSALConfiguration {
  auth: {
    clientId: string;
    authority?: string;           // Default: 'https://login.microsoftonline.com/common'
    knownAuthorities?: string[];
    redirectUri?: string;         // Platform-specific, auto-generated on Android if omitted
  };
  androidConfigOptions?: MSALAndroidConfigOptions;
}

MSALInteractiveParams

interface MSALInteractiveParams {
  scopes: string[];
  authority?: string;
  promptType?: MSALPromptType;
  loginHint?: string;
  extraQueryParameters?: Record<string, string>;
  extraScopesToConsent?: string[];
  webviewParameters?: MSALWebviewParams;
}

MSALSilentParams

interface MSALSilentParams {
  scopes: string[];
  account: MSALAccount;
  authority?: string;
  forceRefresh?: boolean;
}

MSALSignoutParams

interface MSALSignoutParams {
  account: MSALAccount;
  signoutFromBrowser?: boolean;   // iOS only, default: false
  webviewParameters?: MSALWebviewParams;
}

MSALResult

interface MSALResult {
  accessToken: string;
  account: MSALAccount;
  expiresOn: number;              // Unix timestamp (seconds)
  idToken?: string;
  scopes: string[];
  tenantId?: string;
}

MSALAccount

interface MSALAccount {
  identifier: string;
  environment?: string;
  tenantId: string;
  username: string;
  claims?: object;
}

MSALPromptType

enum MSALPromptType {
  SELECT_ACCOUNT = 0,
  LOGIN = 1,
  CONSENT = 2,
  WHEN_REQUIRED = 3,
  DEFAULT = WHEN_REQUIRED,
}

MSALWebviewParams (iOS)

interface MSALWebviewParams {
  ios_prefersEphemeralWebBrowserSession?: boolean;  // iOS 13+
  ios_webviewType?: Ios_MSALWebviewType;
  ios_presentationStyle?: Ios_ModalPresentationStyle;
}

MSALAndroidConfigOptions

interface MSALAndroidConfigOptions {
  authorization_user_agent?: 'DEFAULT' | 'BROWSER' | 'WEBVIEW';
  broker_redirect_uri_registered?: boolean;
  preferred_browser?: MSALAndroidPreferredBrowser;
  browser_safelist?: {
    browser_package_name: string;
    browser_signature_hashes: string[];
    browser_use_customTab: boolean;
  }[];
  http?: { connect_timeout?: number; read_timeout?: number };
  logging?: {
    pii_enabled?: boolean;
    log_level?: 'ERROR' | 'WARNING' | 'INFO' | 'VERBOSE';
    logcat_enabled?: boolean;
  };
  multiple_clouds_supported?: boolean;
}

B2C Example

import PublicClientApplication, {
  MSALConfiguration,
  MSALInteractiveParams,
} from 'react-native-msal2';

const b2cConfig: MSALConfiguration = {
  auth: {
    clientId: '<your-client-id>',
    authority: 'https://<tenant>.b2clogin.com/tfp/<tenant>.onmicrosoft.com/<sign-in-policy>',
    knownAuthorities: ['https://<tenant>.b2clogin.com'],
  },
};

const pca = new PublicClientApplication(b2cConfig);
await pca.init();

const result = await pca.acquireToken({
  scopes: ['https://<tenant>.onmicrosoft.com/<api-id>/access_as_user'],
});

Troubleshooting

  • "PublicClientApplication is not initialized" — Ensure you call await pca.init() before any other method.
  • iOS redirect issues — Verify your URL scheme in Info.plist matches the redirect URI registered in Azure Portal, and that AppDelegate handles the MSAL response.
  • Android signature hash mismatch — Regenerate your signature hash and ensure it matches the redirect URI in Azure Portal. Debug and release builds use different keystores.
  • B2C authority not recognized — Make sure the authority URL follows the pattern https://<tenant>.b2clogin.com/tfp/<tenant>.onmicrosoft.com/<policy> and is included in knownAuthorities.
  • Silent token acquisition fails — The refresh token may have expired. Fall back to acquireToken (interactive) and catch the error from acquireTokenSilent.

Development

Build

npm run build

Output is in /dist.

Tests

npm test
npm run test:watch   # watch mode

Preview App

Create a test app and run it on a device:

npm run app
cd app
npm run ios    # or npm run android

Auto-copy plugin changes to the app:

npm run watch

License

MIT