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

@betabridge/azure-ad-auth-react

v3.1.0

Published

Simple Azure AD Authentication Library for React - Plug and Play Solution

Readme

Azure AD Authentication for React

🚀 Simple and powerful Azure Active Directory authentication for React - Plug and play solution!

Overview

A comprehensive Azure AD authentication library for React applications. No B2C complexity - just simple, straightforward Azure AD integration.

Features

Simple Azure AD Integration - Works with regular Azure Active Directory
Multi-tenant Support - Support for 'common', 'organizations', or specific tenants
TypeScript Ready - Full TypeScript support with type definitions
React Hooks - Modern React hooks API
Pre-built Components - Ready-to-use UI components
Secure - Built on Microsoft MSAL
Zero Config - Sensible defaults, minimal setup

Installation

npm install @betabridge/azure-ad-auth-react
# or
yarn add @betabridge/azure-ad-auth-react

Quick Start

1. Basic Setup

import { AuthProvider, useAuth } from '@betabridge/azure-ad-auth-react';

const config = {
  tenantId: 'your-tenant-id',        // Your Azure AD tenant ID
  clientId: 'your-client-id',         // Your app client ID
  redirectUri: 'http://localhost:3000',
  postLogoutRedirectUri: 'http://localhost:3000',
  scope: ['openid', 'profile', 'email', 'User.Read']
};

function App() {
  return (
    <AuthProvider config={config}>
      <MyApp />
    </AuthProvider>
  );
}

function MyApp() {
  const { isAuthenticated, user, login, logout } = useAuth();

  return (
    <div>
      {isAuthenticated ? (
        <>
          <h1>Welcome {user?.name}!</h1>
          <button onClick={logout}>Logout</button>
        </>
      ) : (
        <button onClick={login}>Login with Azure AD</button>
      )}
    </div>
  );
}

2. Using Pre-built Components

import { 
  AuthProvider, 
  LoginButton, 
  LogoutButton, 
  UserProfile 
} from '@betabridge/azure-ad-auth-react';

function App() {
  return (
    <AuthProvider config={config}>
      <div>
        <LoginButton />
        <LogoutButton />
        <UserProfile />
      </div>
    </AuthProvider>
  );
}

Configuration

AzureADConfig

interface AzureADConfig {
  // Required
  tenantId: string;              // Your tenant ID or 'common'/'organizations'
  clientId: string;              // Application (client) ID
  redirectUri: string;           // Where to redirect after login
  postLogoutRedirectUri: string; // Where to redirect after logout
  scope: string[];               // OAuth scopes

  // Optional
  authority?: string;            // Custom authority URL
  cacheLocation?: 'localStorage' | 'sessionStorage';
  storeAuthStateInCookie?: boolean;
  loginHint?: string;
  domainHint?: string;
  prompt?: 'login' | 'select_account' | 'consent' | 'none';
}

Tenant ID Options

| Value | Description | Use Case | |-------|-------------|----------| | GUID | Specific tenant ID | Single organization | | 'common' | Any Microsoft account | Multi-tenant + personal | | 'organizations' | Work/school only | Multi-tenant enterprise | | 'consumers' | Personal accounts only | Consumer apps |

Common Configurations

Single Tenant (One Organization)

const config = {
  tenantId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
  clientId: 'your-client-id',
  redirectUri: 'http://localhost:3000',
  postLogoutRedirectUri: 'http://localhost:3000',
  scope: ['openid', 'profile', 'email', 'User.Read']
};

Multi-Tenant (Any Microsoft Account)

const config = {
  tenantId: 'common',  // Anyone with a Microsoft account
  clientId: 'your-client-id',
  redirectUri: 'http://localhost:3000',
  postLogoutRedirectUri: 'http://localhost:3000',
  scope: ['openid', 'profile', 'email', 'User.Read']
};

Organizations Only

const config = {
  tenantId: 'organizations',  // Work/school accounts only
  clientId: 'your-client-id',
  redirectUri: 'http://localhost:3000',
  postLogoutRedirectUri: 'http://localhost:3000',
  scope: ['openid', 'profile', 'email', 'User.Read']
};

API Reference

Hooks

useAuth()

Main authentication hook.

const {
  isAuthenticated,  // boolean
  user,            // User object or null
  login,           // () => Promise<void>
  logout,          // () => Promise<void>
  loading,         // boolean
  error,           // string or null
  getAccessToken,  // (scopes?: string[]) => Promise<string | null>
  refreshToken,    // () => Promise<void>
  clearError       // () => void
} = useAuth();

useMsal()

Direct access to MSAL instance.

const { instance, accounts } = useMsal();

useProtectedRoute()

For route protection.

const { isAllowed } = useProtectedRoute();

Components

<AuthProvider>

Wraps your app to provide authentication context.

<AuthProvider config={azureADConfig}>
  {children}
</AuthProvider>

<LoginButton>

Pre-styled login button.

<LoginButton />

Props:

  • text?: string - Button text (default: "Sign In")
  • className?: string - Custom CSS class
  • style?: React.CSSProperties - Inline styles
  • onClick?: () => void - Custom click handler

<LogoutButton>

Pre-styled logout button.

<LogoutButton />

Props:

  • text?: string - Button text (default: "Sign Out")
  • className?: string - Custom CSS class
  • style?: React.CSSProperties - Inline styles
  • onClick?: () => void - Custom click handler

<UserProfile>

Displays user information.

<UserProfile />

Props:

  • className?: string - Custom CSS class
  • style?: React.CSSProperties - Inline styles
  • showEmail?: boolean - Show email (default: true)
  • showName?: boolean - Show name (default: true)

<ProtectedRoute>

Protects routes requiring authentication.

<ProtectedRoute>
  <Dashboard />
</ProtectedRoute>

Props:

  • redirectPath?: string - Where to redirect if not authenticated
  • fallback?: ReactNode - What to show while checking auth

Azure Portal Setup

Step 1: Register Your Application

  1. Go to Azure Portal
  2. Navigate to Azure Active Directory
  3. Select App registrationsNew registration

Step 2: Configure Registration

  • Name: Your application name
  • Supported account types: Choose based on your needs
    • Single tenant (your organization only)
    • Multi-tenant (any Azure AD)
    • Multi-tenant + personal Microsoft accounts
  • Redirect URI:
    • Type: Single-page application (SPA)
    • URI: http://localhost:3000 (for development)

Step 3: Get Your Credentials

From the app Overview page, copy:

  • Application (client) ID → use as clientId
  • Directory (tenant) ID → use as tenantId

Step 4: Configure Authentication

  1. Go to Authentication section
  2. Add redirect URIs for all environments
  3. Enable ID tokens and Access tokens
  4. Add logout URLs

Step 5: Set API Permissions

  1. Go to API permissions
  2. Click Add a permission
  3. Select Microsoft GraphDelegated permissions
  4. Add these permissions:
    • openid
    • profile
    • email
    • User.Read
  5. Click Grant admin consent (if you're admin)

Advanced Usage

Custom Login Options

const { login } = useAuth();

// Login with specific options
await login({
  scopes: ['Mail.Read', 'Calendars.Read'],
  loginHint: '[email protected]',
  domainHint: 'organizations',
  prompt: 'select_account'
});

Get Access Token

const { getAccessToken } = useAuth();

const token = await getAccessToken(['User.Read']);
console.log(token);

Call Microsoft Graph API

const { getAccessToken } = useAuth();

async function getUserData() {
  const token = await getAccessToken(['User.Read']);
  
  const response = await fetch('https://graph.microsoft.com/v1.0/me', {
    headers: {
      'Authorization': `Bearer ${token}`
    }
  });
  
  return response.json();
}

Protected Routes with React Router

import { BrowserRouter, Routes, Route } from 'react-router-dom';
import { ProtectedRoute } from '@betabridge/azure-ad-auth-react';

function App() {
  return (
    <AuthProvider config={config}>
      <BrowserRouter>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route 
            path="/dashboard" 
            element={
              <ProtectedRoute>
                <Dashboard />
              </ProtectedRoute>
            } 
          />
        </Routes>
      </BrowserRouter>
    </AuthProvider>
  );
}

TypeScript Support

Full TypeScript support with comprehensive type definitions:

import type { 
  AzureADConfig, 
  User, 
  AuthState, 
  LoginOptions 
} from '@betabridge/azure-ad-auth-react';

Common Issues

Reply URL Mismatch

Error: "AADSTS50011: The reply URL does not match"

Solution: Add your redirect URI in Azure Portal → App Registration → Authentication

User Has Not Consented

Error: "AADSTS65001: User has not consented"

Solution:

  • Grant admin consent in API permissions
  • Or add prompt: 'consent' to login options

Login Popup Blocked

Solution:

  • Allow popups in browser settings
  • Or use redirect flow instead

Examples

Check out the /examples directory for complete working examples.

Browser Support

  • Chrome (latest)
  • Firefox (latest)
  • Safari (latest)
  • Edge (latest)

Requirements

  • React >= 16.8.0
  • react-dom >= 16.8.0

License

MIT

Support

  • 📖 Documentation: See this file
  • 🐛 Issues: Report on GitHub
  • 💬 Questions: Open a discussion

Links


Made with ❤️ for the React community