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.
What this skill does
# 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 ```bash # Frontend (React SPA) npm install @azure/msal-react @azure/msal-browser # Backend (Cloudflare Workers) npm install jose ``` ### 2. Azure Portal Setup 1. Go to **Microsoft Entra ID** → **App registrations** → **New registration** 2. Set **Redirect URI** to `http://localhost:5173` (SPA type) 3. Note the **Application (client) ID** and **Directory (tenant) ID** 4. Under **Authentication**: - Enable **Access tokens** and **ID tokens** - Add production redirect URI 5. Under **API permissions**: - Add `User.Read` (Microsoft Graph) - Grant admin consent if required --- ## Frontend: MSAL React Setup ### Configuration (src/auth/msal-config.ts) ```typescript import { Configuration, LogLevel } from "@azure/msal-browser"; export const msalConfig: Configuration = { auth: { clientId: import.meta.env.VITE_AZURE_CLIENT_ID, authority: `https://login.microsoftonline.com/${import.meta.env.VITE_AZURE_TENANT_ID}`, redirectUri: window.location.origin, postLogoutRedirectUri: window.location.origin, navigateToLoginRequestUrl: true, }, cache: { cacheLocation: "localStorage", // or "sessionStorage" storeAuthStateInCookie: true, // Required for Safari/Edge issues }, system: { loggerOptions: { logLevel: LogLevel.Warning, loggerCallback: (level, message) => { if (level === LogLevel.Error) console.error(message); }, }, }, }; // Scopes for token requests export const loginRequest = { scopes: ["User.Read", "openid", "profile", "email"], }; // Scopes for API calls (add your API scope here) export const apiRequest = { scopes: [`api://${import.meta.env.VITE_AZURE_CLIENT_ID}/access_as_user`], }; ``` ### MsalProvider Setup (src/main.tsx) ```typescript import React from "react"; import ReactDOM from "react-dom/client"; import { PublicClientApplication, EventType } from "@azure/msal-browser"; import { MsalProvider } from "@azure/msal-react"; import { msalConfig } from "./auth/msal-config"; import App from "./App"; // CRITICAL: Initialize MSAL outside component tree to prevent re-instantiation const msalInstance = new PublicClientApplication(msalConfig); // Handle redirect promise on page load msalInstance.initialize().then(() => { // Set active account after redirect // IMPORTANT: Use getAllAccounts() (returns array), NOT getActiveAccount() (returns single account or null) const accounts = msalInstance.getAllAccounts(); if (accounts.length > 0) { msalInstance.setActiveAccount(accounts[0]); } // Listen for sign-in events msalInstance.addEventCallback((event) => { if (event.eventType === EventType.LOGIN_SUCCESS && event.payload) { const account = (event.payload as { account: any }).account; msalInstance.setActiveAccount(account); } }); ReactDOM.createRoot(document.getElementById("root")!).render( <React.StrictMode> <MsalProvider instance={msalInstance}> <App /> </MsalProvider> </React.StrictMode> ); }); ``` ### Protected Route Component ```typescript import { useMsal, useIsAuthenticated } from "@azure/msal-react"; import { InteractionStatus } from "@azure/msal-browser"; import { loginRequest } from "./msal-config"; export function ProtectedRoute({ children }: { children: React.ReactNode }) { const { instance, inProgress } = useMsal(); const isAuthenticated = useIsAuthenticated(); // Wait for MSAL to finish any in-progress operations if (inProgress !== InteractionStatus.None) { return <div>Loading...</div>; } if (!isAuthenticated) { // Trigger login redirect instance.loginRedirect(loginRequest); return <div>Redirecting to login...</div>; } return <>{children}</>; } ``` ### Acquiring Tokens for API Calls ```typescript import { useMsal } from "@azure/msal-react"; import { InteractionRequiredAuthError } from "@azure/msal-browser"; import { apiRequest } from "./msal-config"; export function useApiToken() { const { instance, accounts } = useMsal(); async function getAccessToken(): Promise<string | null> { if (accounts.length === 0) return null; const request = { ...apiRequest, account: accounts[0], }; try { // Try silent token acquisition first const response = await instance.acquireTokenSilent(request); return response.accessToken; } catch (error) { if (error instanceof InteractionRequiredAuthError) { // Silent acquisition failed, need interactive login // This handles expired refresh tokens (AADSTS700084) await instance.acquireTokenRedirect(request); return null; } throw error; } } return { getAccessToken }; } ``` --- ## 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) ```typescript 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
Related in Ads & Marketing
ads
IncludedMulti-platform paid advertising audit and optimization skill. Analyzes Google, Meta, YouTube, LinkedIn, TikTok, Microsoft, and Apple Ads. 250+ checks with scoring, parallel agents, industry templates, and AI creative generation.
banana
IncludedAI image generation Creative Director powered by Google Gemini Nano Banana models. Use this skill for ANY request involving image creation, editing, visual asset production, or creative direction. Triggers on: generate an image, create a photo, edit this picture, design a logo, make a banner, visual for my anything, and all /banana commands. Handles text-to-image, image editing, multi-turn creative sessions, batch workflows, and brand presets.
rpg-migration-analyzer
IncludedAnalyzes legacy RPG (Report Program Generator) programs from AS/400 and IBM i systems for migration to modern Java applications. Extracts business logic from RPG III/IV/ILE source code, identifies data structures (D-specs), file operations (F-specs), program dependencies (CALLB/CALLP), and converts RPG constructs to Java equivalents. Generates migration reports, complexity estimates, and Java implementation strategies with POJO classes, JPA entities, and service methods. Use when modernizing AS/400 or IBM i legacy systems, analyzing RPG source files (.rpg, .rpgle, .RPGLE), converting RPG to Java, mapping data specifications to Java classes, planning legacy system migration, or when user mentions RPG analysis, Report Program Generator, RPG III/IV/ILE, AS/400 modernization, IBM i migration, packed decimal conversion, or mainframe application rewrite.
brand-library-architect
IncludedBuild a complete brand library for a product — visual asset render pipeline, brand documentation set (BRAND, COPY, MANIFESTO, BIOS, FAQ, GLOSSARY, TONE, PRICING), open-source convention files (README, CONTRIBUTING, SECURITY, CODE_OF_CONDUCT), and a self-contained press kit. This skill should be used when the user asks to "build a brand library / brand kit / press kit / brand assets" for a product, "set up a brand library workflow," "create a positioning manifesto plus visual identity," or any combination of brand documentation + visual asset pipeline. Apply phase-by-phase or run end-to-end. Templates are product-agnostic and use {{TOKEN}} placeholders the skill prompts the user to fill.
writing-tech-post
IncludedAuthors engineering blog posts end-to-end: launch deep-dives, incident postmortems, architecture migrations, performance case studies, tutorials, AI/agent system writeups, security disclosures, and research-to-product translations. Picks the correct archetype, plans the abstraction ladder, enforces an evidence cadence (diagrams, benchmarks, profiles, traces, code, ablations), tunes voice against publisher house styles (Datadog, Vercel, GitHub, AWS, Meta, Cloudflare, Jane Street), and runs a pre-publish gate for narrative momentum and disclosure ethics. Use when drafting a new engineering post, restructuring a draft that feels flat, deciding which evidence form belongs where, validating that depth and product context are balanced, or preparing a postmortem, migration, or performance narrative for external publication. Do not use for API reference documentation, README authoring, marketing copy, release notes, generic SEO content, ghost-written executive thought leadership, or non-engineering long-form essays.
blog-google
IncludedGoogle API integration for blog performance: PageSpeed Insights, CrUX Core Web Vitals with 25-week history, Search Console performance, URL Inspection, Indexing API, GA4 organic traffic, NLP entity analysis for E-E-A-T, YouTube video search for embedding, and Google Ads Keyword Planner. Progressive feature availability based on credential tier (API key, OAuth/service account, GA4, Ads). Shares config with claude-seo at ~/.config/claude-seo/google-api.json. Use when user says "google data", "page speed", "core web vitals", "search console", "indexation", "GA4", "keyword research", "nlp entities", "blog performance", "youtube search", "google api setup".