@betabridge/azure-ad-auth-react
v3.1.0
Published
Simple Azure AD Authentication Library for React - Plug and Play Solution
Maintainers
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-reactQuick 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 classstyle?: React.CSSProperties- Inline stylesonClick?: () => void- Custom click handler
<LogoutButton>
Pre-styled logout button.
<LogoutButton />Props:
text?: string- Button text (default: "Sign Out")className?: string- Custom CSS classstyle?: React.CSSProperties- Inline stylesonClick?: () => void- Custom click handler
<UserProfile>
Displays user information.
<UserProfile />Props:
className?: string- Custom CSS classstyle?: React.CSSProperties- Inline stylesshowEmail?: 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 authenticatedfallback?: ReactNode- What to show while checking auth
Azure Portal Setup
Step 1: Register Your Application
- Go to Azure Portal
- Navigate to Azure Active Directory
- Select App registrations → New 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
- Go to Authentication section
- Add redirect URIs for all environments
- Enable ID tokens and Access tokens
- Add logout URLs
Step 5: Set API Permissions
- Go to API permissions
- Click Add a permission
- Select Microsoft Graph → Delegated permissions
- Add these permissions:
openidprofileemailUser.Read
- 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
