Basic information
About azure-auth
Microsoft Entra ID (Azure AD) authentication for React SPAs with MSAL.js and Cloudflare Workers JWT validation using jose library. Full-stack pattern with Authorization Code Flow + PKCE. Prevents 8 documented errors. Use when: implementing Microsoft SSO, troubleshooting AADSTS50058 loops, AADSTS700084 refresh token errors, React Router redirects, setActiveAccount re-render issues, or validating Entra ID tokens in Workers.
azure-auth is an agent skill listed in the AddMCP.net directory, published by openclaw. Source code is hosted on github.com.
Overview
What is azure-auth?
name: azure-auth description: | Microsoft Entra ID (Azure AD) authentication for React SPAs with MSAL.js and Cloudflare Workers JWT validation using jose library. Full-stack pattern with Authorization Code Flow + PKCE. Prevents 8 documented errors.
Use when: implementing Microsoft SSO, troubleshooting AADSTS50058 loops, AADSTS700084 refresh token errors, React Router redirects, setActiveAccount re-render issues, or validating Entra ID tokens in Workers. user-invocable: true
Azure Auth - Microsoft Entra ID for React + Cloudflare Workers
Package Versions: @azure/[email protected], @azure/[email protected], [email protected] Breaking Changes: MSAL v4→v5 migration (January 2026), Azure AD B2C sunset (May 2025 - new signups blocked, existing until 2030), ADAL retirement (Sept 2025 - complete) Last Updated: 2026-01-21
Architecture Overview
┌─────────────────────┐ ┌──────────────────────┐ ┌─────────────────────┐
│ React SPA │────▶│ Microsoft Entra ID │────▶│ Cloudflare Worker │
│ @azure/msal-react │ │ (login.microsoft) │ │ jose JWT validation│
└─────────────────────┘ └──────────────────────┘ └─────────────────────┘
│ │
│ Authorization Code + PKCE │
│ (access_token, id_token) │
└──────────────────────────────────────────────────────────┘
Bearer token in Authorization header
Key Constraint: MSAL.js does NOT work in Cloudflare Workers (relies on browser/Node.js APIs). Use jose library for backend token validation.
Quick Start
1. Install Dependencies
# Frontend (React SPA)
npm install @azure/msal-react @azure/msal-browser
# Backend (Cloudflare Workers)
npm install jose
2. Azure Portal Setup
- Go to Microsoft Entra ID → App registrations → New registration
- Set Redirect URI to
http://localhost:5173(SPA type) - Note the Application (client) ID and Directory (tenant) ID
- Under Authentication:
- Enable Access tokens and ID tokens
- Add production redirect URI
- Under API permissions:
- Add
User.Read(Microsoft Graph) - Grant admin consent if required
Frontend: MSAL React Setup
Backend: Cloudflare Workers JWT Validation
Why jose Instead of MSAL
MSAL.js relies on browser APIs (localStorage, sessionStorage) and Node.js crypto modules that don't exist in Cloudflare Workers' V8 isolate runtime. The jose library is pure JavaScript and works perfectly in Workers.
JWT Validation (src/auth/validate-token.ts)
import * as jose from "jose";
interface EntraTokenPayload {
aud: string; // Audience (your client ID or API URI)
iss: string; // Issuer (https://login.microsoftonline.com/{tenant}/v2.0)
sub: string; // Subject (user's unique ID)
oid: string; // Object ID (user's Azure AD object ID)
preferred_username: string;
name: string;
email?: string;
roles?: string[]; // App roles if configured
scp?: string; // Scopes (space-separated)
}
// Cache JWKS to avoid fetching on every request
let jwksCache: jose.JWTVerifyGetKey | null = null;
let jwksCacheTime = 0;
const JWKS_CACHE_DURATION = 3600000; // 1 hour
async function getJWKS(tenantId: string): Promise<jose.JWTVerifyGetKey> {
const now = Date.now();
if (jwksCache && now - jwksCacheTime < JWKS_CACHE_DURATION) {
return jwksCache;
}
// CRITICAL: Azure AD JWKS is NOT at .well-known/jwks.json
// Must fetch from openid-configuration first
const configUrl = `https://login.microsoftonline.com/${tenantId}/v2.0/.well-known/openid-configuration`;
const configResponse = await fetch(configUrl);
const config = await configResponse.json() as { jwks_uri: string };
// Now fetch JWKS from the correct URL
jwksCache = jose.createRemoteJWKSet(new URL(config.jwks_uri));
jwksCacheTime = now;
return jwksCache;
}
export async function validateEntraToken(
token: string,
env: {
AZURE_TENANT_ID: string;
AZURE_CLIENT_ID: string;
}
): Promise<EntraTokenPayload | null> {
try {
const jwks = await getJWKS(env.AZURE_TENANT_ID);
const { payload } = await jose.jwtVerify(token, jwks, {
issuer: `https://login.microsoftonline.com/${env.AZURE_TENANT_ID}/v2.0`,
audience: env.AZURE_CLIENT_ID, // or your API URI: api://{client_id}
});
return payload as unknown as EntraTokenPayload;
} catch (error) {
console.error("Token validation failed:", error);
return null;
}
}
Worker Middleware Pattern
import { validateEntraToken } from "./auth/validate-token";
export default {
async fetch(request: Request, env: Env): Promise<Response> {
// Skip auth for public routes
const url = new URL(request.url);
if (url.pathname === "/" || url.pathname.startsWith("/public")) {
return handlePublicRoute(request, env);
}
// Extract Bearer token
const authHeader = request.headers.get("Authorization");
if (!authHeader?.startsWith("Bearer ")) {
return new Response(JSON.stringify({ error: "Missing authorization" }), {
status: 401,
headers: { "Content-Type": "application/json" },
});
}
const token = authHeader.slice(7);
const user = await validateEntraToken(token, env);
if (!user) {
return new Response(JSON.stringify({ error: "Invalid token" }), {
status: 401,
headers: { "Content-Type": "application/json" },
});
}
// Add user to request context
const requestWithUser = new Request(request);
// Pass user info downstream (e.g., via headers or context)
return handleProtectedRoute(request, env, user);
},
};
Common Errors & Fixes
Multi-Tenant vs Single-Tenant
Single Tenant (Recommended for Enterprise)
authority: `https://login.microsoftonline.com/${TENANT_ID}`,
- Only users from your organization can sign in
- Token issuer:
https://login.microsoftonline.com/{tenant_id}/v2.0
Multi-Tenant
authority: "https://login.microsoftonline.com/common",
// or for work/school accounts only:
authority: "https://login.microsoftonline.com/organizations",
- Users from any Azure AD tenant can sign in
- Token issuer varies by user's tenant
- Backend validation must handle multiple issuers:
// Multi-tenant issuer validation
const tenantId = payload.tid; // Tenant ID from token
const expectedIssuer = `https://login.microsoftonline.com/${tenantId}/v2.0`;
if (payload.iss !== expectedIssuer) {
throw new Error("Invalid issuer");
}
Environment Variables
Frontend (.env)
VITE_AZURE_CLIENT_ID=your-client-id-guid
VITE_AZURE_TENANT_ID=your-tenant-id-guid
Backend (wrangler.jsonc)
{
"name": "my-api",
"vars": {
"AZURE_TENANT_ID": "your-tenant-id-guid",
"AZURE_CLIENT_ID": "your-client-id-guid"
}
}
Azure AD B2C Sunset
Timeline:
- May 1, 2025: Azure AD B2C no longer available for new customer signups
- March 15, 2026: Azure AD B2C P2 discontinued for all customers
- May 2030: Microsoft will continue supporting existing B2C customers with standard support
Source: Microsoft Q&A
Existing B2C Customers: Can continue using B2C until 2030, but should plan migration to Entra External ID.
New Projects: Use Microsoft Entra External ID for consumer/customer identity scenarios.
Migration Status: As of January 2026, automated migration tools are in testing phase. Manual migration guidance available at Microsoft Learn.
Migration Path:
- Different authority URL format (
{tenant}.ciamlogin.comvs{tenant}.b2clogin.com) - Updated SDK support (same MSAL libraries)
- New pricing model (consumption-based)
- Self-Service Password Reset (SSPR) approach available for user migration
- Seamless migration samples on GitHub (preview)
See: https://learn.microsoft.com/en-us/entra/external-id/ Migration Guide: https://learn.microsoft.com/en-us/entra/external-id/customers/how-to-migrate-users
ADAL Retirement (Complete)
Status: Azure AD Authentication Library (ADAL) was retired on September 30, 2025. Apps using ADAL no longer receive security updates.
If you're migrating from ADAL:
- ADAL → MSAL migration is required
- ADAL used v1.0 endpoints; MSAL uses v2.0 endpoints
- Token cache format differs - users must re-authenticate
- Scopes replace "resources" in token requests
Key Migration Changes:
// ADAL (deprecated) - resource-based
acquireToken({ resource: "https://graph.microsoft.com" })
// MSAL (current) - scope-based
acquireTokenSilent({ scopes: ["https://graph.microsoft.com/User.Read"] })
See: https://learn.microsoft.com/en-us/entra/msal/javascript/migration/msal-net-migration
Comments
No comments yet
Be the first to share feedback about this listing. Sign in to leave a comment.
Sign In