Skip to content

Skills for Claude Code CLI such as full stack dev Cloudflare, React, Tailwind v4, and AI integrations.

feat(azure-auth): Add Azure AD/Entra ID authentication skill

Jez80d6a4676494
diff --git a/skills/azure-auth/.claude-plugin/plugin.json b/skills/azure-auth/.claude-plugin/plugin.json
new file mode 100644
index 00000000..81d5a206
--- /dev/null
+++ b/skills/azure-auth/.claude-plugin/plugin.json
@@ -0,0 +1,12 @@
+{
+ "name": "azure-auth",
+ "description": "Microsoft Entra ID (Azure AD) authentication for React SPAs with MSAL.js and Cloudflare Workers backend JWT validation. Full-stack pattern: MSAL React for frontend auth flows, jose library for Workers token validation (MSAL.js doesnt work in Workers). CRITICAL: Azure AD JWKS endpoint is NOT at standard .well-known/jwks.json - must fetch from openid-configuration first. MSAL v3.0.23 + msal-browser v4.27.0 use Authorization Code Flow with PKCE (no implicit flow). Use when: implementing Microsoft/A",
+ "version": "1.0.0",
+ "author": {
+ "name": "Jeremy Dawes",
+ "email": "[email protected]"
+ },
+ "license": "MIT",
+ "repository": "https://github.com/jezweb/claude-skills",
+ "keywords": []
+}
diff --git a/skills/azure-auth/README.md b/skills/azure-auth/README.md
new file mode 100644
index 00000000..5cebb3fa
--- /dev/null
+++ b/skills/azure-auth/README.md
@@ -0,0 +1,72 @@
+# azure-auth
+
+Microsoft Entra ID (Azure AD) authentication for React SPAs + Cloudflare Workers backend.
+
+## Auto-Trigger Keywords
+
+This skill activates when you mention:
+
+### Technologies
+- Azure AD, Azure Active Directory, Microsoft Entra ID, Entra ID
+- MSAL, MSAL.js, msal-react, msal-browser, @azure/msal-react, @azure/msal-browser
+- Microsoft authentication, Microsoft SSO, Microsoft login
+- Azure B2C, Entra External ID
+
+### Use Cases
+- Microsoft SSO, Azure SSO, corporate SSO, enterprise SSO
+- Office 365 login, Microsoft 365 authentication
+- Azure AD token validation, Entra token validation
+- JWT validation Azure, validate Azure token
+- JWKS Azure, Azure AD JWKS
+
+### Errors
+- AADSTS50058, AADSTS700084, AADSTS65001, AADSTS90102
+- no_cached_authority_error
+- interaction_in_progress
+- redirect loop MSAL, infinite loop MSAL
+- acquireTokenSilent failed
+- refresh token expired SPA
+
+### Patterns
+- Azure AD React, MSAL React setup
+- Azure AD Cloudflare Workers
+- MsalProvider, PublicClientApplication
+- Authorization Code Flow PKCE Azure
+- Multi-tenant Azure AD
+
+## What This Skill Provides
+
+1. **MSAL React Setup** - Configuration, provider, hooks
+2. **Protected Routes** - Auth-gated components with proper loading states
+3. **Token Acquisition** - Silent + interactive fallback patterns
+4. **Workers JWT Validation** - jose-based validation (MSAL doesn't work in Workers)
+5. **Error Prevention** - AADSTS codes, redirect loops, JWKS quirks
+6. **Multi-Tenant Support** - Single vs multi-tenant patterns
+
+## Key Files
+
+- `SKILL.md` - Complete documentation
+- `templates/msal-config.ts` - MSAL configuration
+- `templates/msal-provider.tsx` - React provider setup
+- `templates/protected-route.tsx` - Auth-protected component wrapper
+- `templates/workers-jwt-validation.ts` - Cloudflare Workers token validation
+- `rules/azure-auth.md` - Correction rules for common mistakes
+- `references/aadsts-error-codes.md` - Error code reference
+
+## Critical Notes
+
+1. **MSAL.js does NOT work in Cloudflare Workers** - Use jose library for backend
+2. **Azure AD JWKS URL is non-standard** - Fetch from openid-configuration first
+3. **SPA refresh tokens expire in 24 hours** - Handle InteractionRequiredAuthError
+4. **storeAuthStateInCookie: true** - Required for Safari/Edge compatibility
+5. **Azure AD B2C sunset May 2025** - Use Entra External ID for new consumer apps
+
+## Package Versions
+
+```json
+{
+ "@azure/msal-react": "3.0.23",
+ "@azure/msal-browser": "4.27.0",
+ "jose": "5.9.6"
+}
+```
diff --git a/skills/azure-auth/SKILL.md b/skills/azure-auth/SKILL.md
new file mode 100644
index 00000000..c7c71f36
--- /dev/null
+++ b/skills/azure-auth/SKILL.md
@@ -0,0 +1,544 @@
+---
+name: azure-auth
+description: |
+ Microsoft Entra ID (Azure AD) authentication for React SPAs with MSAL.js and Cloudflare Workers backend JWT validation. Full-stack pattern: MSAL React for frontend auth flows, jose library for Workers token validation (MSAL.js doesn't work in Workers).
+
+ CRITICAL: Azure AD JWKS endpoint is NOT at standard .well-known/jwks.json - must fetch from openid-configuration first. MSAL v3.0.23 + msal-browser v4.27.0 use Authorization Code Flow with PKCE (no implicit flow).
+
+ Use when: implementing Microsoft/Azure AD SSO, troubleshooting AADSTS50058 infinite loops, AADSTS700084 refresh token expired, React Router v6 redirect loops, NextJS no_cached_authority_error, or validating Entra ID tokens in Cloudflare Workers.
+---
+
+# Azure Auth - Microsoft Entra ID for React + Cloudflare Workers
+
+**Package Versions**: @azure/[email protected], @azure/[email protected], [email protected]
+**Breaking Changes**: Azure AD B2C sunset May 2025, MSAL v2→v3 migration
+**Last Updated**: 2025-12-15
+
+---
+
+## 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
+ 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}/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
+
+```typescript
+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
+
+### 1. AADSTS50058 - Silent Sign-In Loop
+
+**Error**: "A silent sign-in request was sent but no user is signed in"
+
+**Cause**: `acquireTokenSilent` called when no cached user exists.
+
+**Fix**:
+```typescript
+// Always check for accounts before silent acquisition
+const accounts = instance.getAllAccounts();
+if (accounts.length === 0) {
+ // No cached user, trigger interactive login
+ await instance.loginRedirect(loginRequest);
+ return;
+}
+```
+
+### 2. AADSTS700084 - Refresh Token Expired
+
+**Error**: "The refresh token was issued to a single page app (SPA), and therefore has a fixed, limited lifetime of 1.00:00:00"
+
+**Cause**: SPA refresh tokens expire after 24 hours. Cannot be extended.
+
+**Fix**:
+```typescript
+try {
+ const response = await instance.acquireTokenSilent(request);
+} catch (error) {
+ if (error instanceof InteractionRequiredAuthError) {
+ // Refresh token expired, need fresh login
+ await instance.acquireTokenRedirect(request);
+ }
+}
+```
+
+### 3. React Router v6 Redirect Loop
+
+**Error**: Infinite redirects between login page and app.
+
+**Cause**: React Router v6 may strip the hash fragment containing auth response.
+
+**Fix**: Use custom NavigationClient:
+```typescript
+import { NavigationClient } from "@azure/msal-browser";
+import { useNavigate } from "react-router-dom";
+
+class CustomNavigationClient extends NavigationClient {
+ private navigate: ReturnType<typeof useNavigate>;
+
+ constructor(navigate: ReturnType<typeof useNavigate>) {
+ super();
+ this.navigate = navigate;
+ }
+
+ async navigateInternal(url: string, options: { noHistory: boolean }) {
+ const relativePath = url.replace(window.location.origin, "");
+ if (options.noHistory) {
+ this.navigate(relativePath, { replace: true });
+ } else {
+ this.navigate(relativePath);
+ }
+ return false; // Prevent MSAL from doing its own navigation
+ }
+}
+
+// In your App component:
+const navigate = useNavigate();
+useEffect(() => {
+ const navigationClient = new CustomNavigationClient(navigate);
+ instance.setNavigationClient(navigationClient);
+}, [instance, navigate]);
+```
+
+### 4. NextJS Dynamic Route Error
+
+**Error**: `no_cached_authority_error` in dynamic routes.
+
+**Cause**: MSAL instance not properly initialized before component renders.
+
+**Fix**: Initialize MSAL in `_app.tsx` before any routing:
+```typescript
+// pages/_app.tsx
+import { PublicClientApplication } from "@azure/msal-browser";
+import { MsalProvider } from "@azure/msal-react";
+import { msalConfig } from "../auth/msal-config";
+
+// Initialize outside component
+const msalInstance = new PublicClientApplication(msalConfig);
+
+// Ensure initialization completes before render
+export default function App({ Component, pageProps }) {
+ const [isInitialized, setIsInitialized] = useState(false);
+
+ useEffect(() => {
+ msalInstance.initialize().then(() => setIsInitialized(true));
+ }, []);
+
+ if (!isInitialized) return <div>Loading...</div>;
+
+ return (
+ <MsalProvider instance={msalInstance}>
+ <Component {...pageProps} />
+ </MsalProvider>
+ );
+}
+```
+
+### 5. Safari/Edge Cookie Issues
+
+**Error**: Auth state lost, infinite loop on Safari or Edge.
+
+**Cause**: These browsers have stricter cookie policies affecting session storage.
+
+**Fix**: Enable cookie storage in MSAL config:
+```typescript
+cache: {
+ cacheLocation: "localStorage",
+ storeAuthStateInCookie: true, // REQUIRED for Safari/Edge
+}
+```
+
+### 6. JWKS URL Not Found (Workers)
+
+**Error**: Failed to fetch JWKS from `.well-known/jwks.json`.
+
+**Cause**: Azure AD doesn't serve JWKS at the standard OpenID Connect path.
+
+**Fix**: Fetch `openid-configuration` first, then use `jwks_uri`:
+```typescript
+// WRONG - Azure AD doesn't use this path
+const jwks = createRemoteJWKSet(
+ new URL(`https://login.microsoftonline.com/${tenantId}/.well-known/jwks.json`)
+);
+
+// CORRECT - Fetch config first
+const config = await fetch(
+ `https://login.microsoftonline.com/${tenantId}/v2.0/.well-known/openid-configuration`
+).then(r => r.json());
+const jwks = createRemoteJWKSet(new URL(config.jwks_uri));
+```
+
+---
+
+## Multi-Tenant vs Single-Tenant
+
+### Single Tenant (Recommended for Enterprise)
+
+```typescript
+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
+
+```typescript
+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**:
+
+```typescript
+// 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)
+
+```bash
+VITE_AZURE_CLIENT_ID=your-client-id-guid
+VITE_AZURE_TENANT_ID=your-tenant-id-guid
+```
+
+### Backend (wrangler.jsonc)
+
+```jsonc
+{
+ "name": "my-api",
+ "vars": {
+ "AZURE_TENANT_ID": "your-tenant-id-guid",
+ "AZURE_CLIENT_ID": "your-client-id-guid"
+ }
+}
+```
+
+---
+
+## Azure AD B2C Sunset Notice
+
+**Effective May 1, 2025**: Azure AD B2C is no longer available for new customers.
+
+**Migration Path**: Use **Microsoft Entra External ID** for consumer/customer identity scenarios.
+
+**Key Differences**:
+- Different authority URL format
+- Updated SDK support
+- New pricing model
+
+See: https://learn.microsoft.com/en-us/entra/external-id/
+
+---
+
+## Resources
+
+- [MSAL React Documentation](https://learn.microsoft.com/en-us/entra/msal/javascript/react/)
+- [Microsoft Entra ID App Registration](https://learn.microsoft.com/en-us/entra/identity-platform/quickstart-register-app)
+- [MSAL.js GitHub Issues](https://github.com/AzureAD/microsoft-authentication-library-for-js/issues)
+- [jose Library](https://github.com/panva/jose)
+- [Cloudflare Workers + Azure AD Blog](https://hajekj.net/2021/11/12/cloudflare-workers-and-azure-ad/)
diff --git a/skills/azure-auth/references/aadsts-error-codes.md b/skills/azure-auth/references/aadsts-error-codes.md
new file mode 100644
index 00000000..fbceeb91
--- /dev/null
+++ b/skills/azure-auth/references/aadsts-error-codes.md
@@ -0,0 +1,273 @@
+# AADSTS Error Codes Reference
+
+Common Azure AD Security Token Service error codes and how to resolve them.
+
+## Authentication Flow Errors
+
+### AADSTS50058 - Silent Sign-In Failed
+
+**Message**: "A silent sign-in request was sent but no user is signed in."
+
+**Cause**: Called `acquireTokenSilent` when no user session exists in cache.
+
+**Fix**:
+```typescript
+const accounts = instance.getAllAccounts();
+if (accounts.length === 0) {
+ // No cached user - must do interactive login first
+ await instance.loginRedirect(loginRequest);
+ return;
+}
+
+// Now safe to try silent acquisition
+const response = await instance.acquireTokenSilent({
+ ...apiRequest,
+ account: accounts[0],
+});
+```
+
+---
+
+### AADSTS700084 - Refresh Token Expired
+
+**Message**: "The refresh token was issued to a single page app (SPA), and therefore has a fixed, limited lifetime of 1.00:00:00, which cannot be extended."
+
+**Cause**: SPA refresh tokens have a 24-hour lifetime that cannot be extended.
+
+**Fix**:
+```typescript
+try {
+ const response = await instance.acquireTokenSilent(request);
+ return response.accessToken;
+} catch (error) {
+ if (error instanceof InteractionRequiredAuthError) {
+ // Refresh token expired, need fresh login
+ await instance.acquireTokenRedirect(request);
+ }
+ throw error;
+}
+```
+
+**Note**: This is by design for SPAs. For longer-lived sessions, consider using a backend that can hold refresh tokens securely.
+
+---
+
+### AADSTS65001 - Consent Not Granted
+
+**Message**: "The user or administrator has not consented to use the application."
+
+**Cause**: Required permissions haven't been consented to by user or admin.
+
+**Fix Options**:
+
+1. **User consent** - User clicks "Accept" on consent prompt
+2. **Admin consent** - Admin grants consent for entire organization
+3. **Prompt for consent**:
+```typescript
+await instance.loginRedirect({
+ ...loginRequest,
+ prompt: "consent", // Force consent dialog
+});
+```
+
+---
+
+### AADSTS90102 - Redirect URI Mismatch
+
+**Message**: "redirect_uri value must match the redirect URI configured for the application."
+
+**Cause**: The redirect URI in code doesn't exactly match Azure Portal configuration.
+
+**Fix**:
+1. Check Azure Portal > App registrations > Authentication > Redirect URIs
+2. Ensure exact match including:
+ - Protocol (http vs https)
+ - Port number (localhost:5173 vs localhost:3000)
+ - Trailing slash (with vs without)
+3. For development, add `http://localhost:5173`
+
+---
+
+### AADSTS50011 - Reply URL Mismatch
+
+**Message**: "The reply URL specified in the request does not match the reply URLs configured for the application."
+
+**Cause**: Similar to AADSTS90102 - redirect URI doesn't match.
+
+**Common issues**:
+- Trailing slash mismatch: `http://localhost:5173` vs `http://localhost:5173/`
+- Protocol mismatch: `http://` vs `https://`
+- Wrong port in development
+
+---
+
+### AADSTS50076 - MFA Required
+
+**Message**: "Due to a configuration change made by your administrator, you must use multi-factor authentication."
+
+**Cause**: Conditional Access policy requires MFA but user hasn't completed it.
+
+**Fix**: This requires user action - complete MFA challenge. Your app should handle this gracefully:
+```typescript
+if (error.errorCode === "50076") {
+ // Trigger interactive login which will show MFA prompt
+ await instance.acquireTokenRedirect(request);
+}
+```
+
+---
+
+### AADSTS50105 - User Not Assigned
+
+**Message**: "The signed in user is not assigned to a role for the application."
+
+**Cause**: Enterprise app requires user assignment, but user isn't assigned.
+
+**Fix**:
+1. Azure Portal > Enterprise applications > Your app
+2. Properties > "Assignment required?" - set to No, or
+3. Users and groups > Add user/group assignment
+
+---
+
+## Token Validation Errors
+
+### AADSTS500011 - Resource Not Found
+
+**Message**: "The resource principal named [name] was not found in the tenant."
+
+**Cause**: The API URI or scope doesn't exist in the tenant.
+
+**Fix**:
+1. Verify scope format: `api://{client-id}/{scope-name}`
+2. Check App Registration > Expose an API > Scopes
+3. Ensure API is in the same tenant or configured for multi-tenant
+
+---
+
+### AADSTS700016 - Application Not Found
+
+**Message**: "Application with identifier '[app-id]' was not found in the directory."
+
+**Cause**: Client ID doesn't exist in the specified tenant.
+
+**Fix**:
+1. Verify client ID is correct
+2. Check tenant ID matches where app is registered
+3. For multi-tenant apps, ensure "Accounts in any organizational directory" is selected
+
+---
+
+### AADSTS7000218 - PKCE Required
+
+**Message**: "The request body must contain the following parameter: 'code_challenge'."
+
+**Cause**: App is configured for PKCE but request doesn't include code challenge.
+
+**Fix**: MSAL v3+ uses PKCE by default. If you see this error:
+1. Ensure you're using @azure/msal-browser v2+ or @azure/msal-react v2+
+2. Don't override the auth flow configuration
+
+---
+
+## Session/Cache Errors
+
+### interaction_in_progress
+
+**Message**: "Interaction is currently in progress. Please ensure that this interaction has been completed before calling an interactive API."
+
+**Cause**: Called an interactive method while another is in progress.
+
+**Fix**:
+```typescript
+import { InteractionStatus } from "@azure/msal-browser";
+
+function MyComponent() {
+ const { inProgress } = useMsal();
+
+ const handleLogin = async () => {
+ // Check if an interaction is already in progress
+ if (inProgress !== InteractionStatus.None) {
+ console.log("Waiting for current interaction to complete...");
+ return;
+ }
+
+ await instance.loginRedirect(loginRequest);
+ };
+}
+```
+
+---
+
+### no_cached_authority_error
+
+**Message**: "No cached authority error."
+
+**Cause**: MSAL couldn't find cached authority metadata, common with NextJS dynamic routes.
+
+**Fix**:
+```typescript
+// Ensure MSAL is initialized before any routing
+// In _app.tsx:
+const [isReady, setIsReady] = useState(false);
+
+useEffect(() => {
+ msalInstance.initialize().then(() => {
+ // Handle redirect promise
+ msalInstance.handleRedirectPromise().then(() => {
+ setIsReady(true);
+ });
+ });
+}, []);
+
+if (!isReady) return <Loading />;
+```
+
+---
+
+## Multi-Tenant Errors
+
+### AADSTS50020 - User Account Not in Tenant
+
+**Message**: "User account from identity provider does not exist in tenant."
+
+**Cause**: User from external tenant trying to access single-tenant app.
+
+**Fix Options**:
+1. Configure app as multi-tenant in Azure Portal
+2. Add user as guest in your tenant
+3. Use `authority: "https://login.microsoftonline.com/common"` for multi-tenant
+
+---
+
+### AADSTS90072 - External User Not Allowed
+
+**Message**: "The tenant doesn't allow external users."
+
+**Cause**: B2B guest access is disabled in the target tenant.
+
+**Fix**: Tenant admin must enable guest access in Azure AD settings.
+
+---
+
+## Quick Reference Table
+
+| Code | Short Name | Quick Fix |
+|------|------------|-----------|
+| AADSTS50058 | No user | Check `getAllAccounts()` before silent acquisition |
+| AADSTS700084 | Refresh expired | Catch `InteractionRequiredAuthError`, redirect to login |
+| AADSTS65001 | No consent | Prompt for consent or request admin consent |
+| AADSTS90102 | URI mismatch | Match redirect URI exactly in Azure Portal |
+| AADSTS50011 | Reply mismatch | Check trailing slashes and protocol |
+| AADSTS50076 | MFA required | Let user complete MFA challenge |
+| AADSTS50105 | Not assigned | Assign user in Enterprise Applications |
+| AADSTS500011 | API not found | Verify scope URI format |
+| AADSTS700016 | App not found | Check client ID and tenant ID |
+
+---
+
+## Resources
+
+- [Azure AD Error Codes Reference](https://learn.microsoft.com/en-us/azure/active-directory/develop/reference-aadsts-error-codes)
+- [MSAL.js Error Handling](https://learn.microsoft.com/en-us/entra/msal/javascript/browser/errors)
+- [Troubleshooting Guide](https://learn.microsoft.com/en-us/azure/active-directory/develop/troubleshoot-publisher-verification)
diff --git a/skills/azure-auth/rules/azure-auth.md b/skills/azure-auth/rules/azure-auth.md
new file mode 100644
index 00000000..20e95d52
--- /dev/null
+++ b/skills/azure-auth/rules/azure-auth.md
@@ -0,0 +1,71 @@
+# Azure Auth Correction Rules
+
+Rules for Microsoft Entra ID (Azure AD) authentication with MSAL React and Cloudflare Workers.
+
+## MSAL Configuration
+
+| If Claude suggests... | Use instead... |
+|----------------------|----------------|
+| `cacheLocation: "sessionStorage"` without cookie flag | Add `storeAuthStateInCookie: true` for Safari/Edge |
+| Creating MSAL instance inside component | Create outside component tree to prevent re-instantiation |
+| Using implicit flow | Authorization Code Flow with PKCE (MSAL v3 default) |
+| `authority: "https://login.microsoftonline.com/common"` for enterprise | Use tenant-specific authority for single-tenant apps |
+
+## Token Acquisition
+
+| If Claude suggests... | Use instead... |
+|----------------------|----------------|
+| `acquireTokenSilent` without checking accounts | Check `getAllAccounts().length > 0` first |
+| Catching generic error on acquireTokenSilent | Catch `InteractionRequiredAuthError` specifically |
+| Ignoring AADSTS700084 | Handle as "refresh token expired, need interactive login" |
+| Calling interactive method without checking inProgress | Check `inProgress !== InteractionStatus.None` first |
+
+## Cloudflare Workers JWT Validation
+
+| If Claude suggests... | Use instead... |
+|----------------------|----------------|
+| Using MSAL.js in Workers | Use jose library (MSAL doesn't work in Workers) |
+| Fetching JWKS from `.well-known/jwks.json` | Fetch from `openid-configuration` first, use `jwks_uri` |
+| Hardcoding JWKS public key | Fetch dynamically and cache (keys rotate) |
+| Single issuer validation for multi-tenant | Validate issuer matches `tid` claim from token |
+
+## React Router Integration
+
+| If Claude suggests... | Use instead... |
+|----------------------|----------------|
+| Using `MsalAuthenticationTemplate` on redirect URI page | Don't render auth components on redirect page |
+| Ignoring hash fragment in React Router v6 | Implement custom `NavigationClient` |
+| Calling `loginRedirect` in render | Use `useEffect` or event handler |
+
+## Azure Portal Configuration
+
+| If Claude suggests... | Use instead... |
+|----------------------|----------------|
+| "Web" platform for SPA | "Single-page application" platform type |
+| Implicit grant only | Enable "Access tokens" and "ID tokens" under Authentication |
+| Skipping redirect URI for localhost | Add `http://localhost:5173` (or your dev port) |
+
+## Common AADSTS Errors
+
+| Error Code | Meaning | Fix |
+|------------|---------|-----|
+| AADSTS50058 | Silent sign-in, no user | Check for cached accounts before silent acquisition |
+| AADSTS700084 | Refresh token expired (24hr SPA limit) | Trigger interactive login |
+| AADSTS65001 | Consent not granted | Request admin consent or prompt user |
+| AADSTS90102 | Redirect URI mismatch | Verify URI in Azure Portal matches exactly |
+| AADSTS50011 | Reply URL doesn't match | Check trailing slashes, http vs https |
+
+## Environment Variables
+
+| If Claude suggests... | Use instead... |
+|----------------------|----------------|
+| Hardcoding client ID | Use `import.meta.env.VITE_AZURE_CLIENT_ID` |
+| Exposing tenant ID in git | Store in `.env` (gitignored) or CI/CD secrets |
+| Using `process.env` in Vite | Use `import.meta.env` for Vite projects |
+
+## Azure AD B2C (Sunset May 2025)
+
+| If Claude suggests... | Use instead... |
+|----------------------|----------------|
+| Setting up new Azure AD B2C | Use Microsoft Entra External ID for consumer apps |
+| B2C authority URL for new projects | Entra External ID authority format |
diff --git a/skills/azure-auth/templates/msal-config.ts b/skills/azure-auth/templates/msal-config.ts
new file mode 100644
index 00000000..9dbead16
--- /dev/null
+++ b/skills/azure-auth/templates/msal-config.ts
@@ -0,0 +1,99 @@
+/**
+ * MSAL Configuration for Microsoft Entra ID (Azure AD)
+ *
+ * Replace environment variables with your Azure app registration values:
+ * - VITE_AZURE_CLIENT_ID: Application (client) ID from Azure Portal
+ * - VITE_AZURE_TENANT_ID: Directory (tenant) ID from Azure Portal
+ */
+
+import { Configuration, LogLevel } from "@azure/msal-browser";
+
+export const msalConfig: Configuration = {
+ auth: {
+ // Application (client) ID from Azure Portal
+ clientId: import.meta.env.VITE_AZURE_CLIENT_ID,
+
+ // Authority URL - single tenant
+ // For multi-tenant, use: "https://login.microsoftonline.com/common"
+ // For work/school only: "https://login.microsoftonline.com/organizations"
+ authority: `https://login.microsoftonline.com/${import.meta.env.VITE_AZURE_TENANT_ID}`,
+
+ // Redirect URI - must match Azure Portal configuration exactly
+ redirectUri: window.location.origin,
+
+ // Where to redirect after logout
+ postLogoutRedirectUri: window.location.origin,
+
+ // Navigate back to the original page after login
+ navigateToLoginRequestUrl: true,
+ },
+
+ cache: {
+ // Where to store auth state
+ // "localStorage" persists across tabs, "sessionStorage" is per-tab
+ cacheLocation: "localStorage",
+
+ // CRITICAL: Required for Safari and Edge compatibility
+ // These browsers have stricter cookie policies that can break auth state
+ storeAuthStateInCookie: true,
+ },
+
+ system: {
+ loggerOptions: {
+ logLevel: LogLevel.Warning,
+ loggerCallback: (level, message, containsPii) => {
+ if (containsPii) return; // Never log PII
+
+ switch (level) {
+ case LogLevel.Error:
+ console.error("[MSAL]", message);
+ break;
+ case LogLevel.Warning:
+ console.warn("[MSAL]", message);
+ break;
+ case LogLevel.Info:
+ console.info("[MSAL]", message);
+ break;
+ case LogLevel.Verbose:
+ console.debug("[MSAL]", message);
+ break;
+ }
+ },
+ },
+ // Prevent popup/iframe timeouts on slow networks
+ windowHashTimeout: 60000,
+ iframeHashTimeout: 6000,
+ loadFrameTimeout: 0,
+ },
+};
+
+/**
+ * Scopes for initial login
+ * - openid, profile, email are standard OIDC scopes
+ * - User.Read allows reading the signed-in user's profile from Microsoft Graph
+ */
+export const loginRequest = {
+ scopes: ["openid", "profile", "email", "User.Read"],
+};
+
+/**
+ * Scopes for calling your own API
+ * Replace with your API's scope URI from Azure Portal:
+ * App Registration > Expose an API > Add a scope
+ *
+ * Format: api://{client_id}/{scope_name}
+ */
+export const apiRequest = {
+ scopes: [`api://${import.meta.env.VITE_AZURE_CLIENT_ID}/access_as_user`],
+};
+
+/**
+ * Scopes for Microsoft Graph API calls
+ * Add additional Graph scopes as needed:
+ * - Mail.Read, Mail.Send for email
+ * - Calendars.Read, Calendars.ReadWrite for calendar
+ * - Files.Read, Files.ReadWrite for OneDrive
+ */
+export const graphRequest = {
+ scopes: ["User.Read"],
+};
diff --git a/skills/azure-auth/templates/msal-provider.tsx b/skills/azure-auth/templates/msal-provider.tsx
new file mode 100644
index 00000000..708d7b31
--- /dev/null
+++ b/skills/azure-auth/templates/msal-provider.tsx
@@ -0,0 +1,167 @@
+/**
+ * MSAL Provider Setup for React Applications
+ *
+ * This file should be imported in your main.tsx or App.tsx.
+ * CRITICAL: MSAL instance must be created OUTSIDE the component tree
+ * to prevent re-instantiation on re-renders.
+ */
+
+import React, { useEffect, useState } from "react";
+import {
+ PublicClientApplication,
+ EventType,
+ EventMessage,
+ AuthenticationResult,
+ InteractionStatus,
+} from "@azure/msal-browser";
+import { MsalProvider, useMsal } from "@azure/msal-react";
+import { msalConfig } from "./msal-config";
+
+// CRITICAL: Create MSAL instance outside component tree
+// This prevents re-initialization on every render
+export const msalInstance = new PublicClientApplication(msalConfig);
+
+/**
+ * Initialize MSAL and set up event handlers
+ * Call this before rendering your app
+ */
+export async function initializeMsal(): Promise<void> {
+ await msalInstance.initialize();
+
+ // Handle redirect response if coming back from login
+ try {
+ const response = await msalInstance.handleRedirectPromise();
+ if (response) {
+ msalInstance.setActiveAccount(response.account);
+ }
+ } catch (error) {
+ console.error("Error handling redirect:", error);
+ }
+
+ // Set active account if one exists
+ const accounts = msalInstance.getAllAccounts();
+ if (accounts.length > 0) {
+ // If multiple accounts, you might want to let user choose
+ // For now, use the first one
+ msalInstance.setActiveAccount(accounts[0]);
+ }
+
+ // Listen for sign-in success to set active account
+ msalInstance.addEventCallback((event: EventMessage) => {
+ if (event.eventType === EventType.LOGIN_SUCCESS && event.payload) {
+ const result = event.payload as AuthenticationResult;
+ msalInstance.setActiveAccount(result.account);
+ }
+
+ if (event.eventType === EventType.LOGOUT_SUCCESS) {
+ msalInstance.setActiveAccount(null);
+ }
+ });
+}
+
+/**
+ * Props for the auth provider wrapper
+ */
+interface AuthProviderProps {
+ children: React.ReactNode;
+ loadingComponent?: React.ReactNode;
+}
+
+/**
+ * Auth Provider Component
+ *
+ * Wraps your app with MsalProvider and handles initialization.
+ * Shows a loading state while MSAL initializes.
+ *
+ * Usage in main.tsx:
+ * ```tsx
+ * import { AuthProvider } from "./auth/msal-provider";
+ *
+ * ReactDOM.createRoot(document.getElementById("root")!).render(
+ * <React.StrictMode>
+ * <AuthProvider>
+ * <App />
+ * </AuthProvider>
+ * </React.StrictMode>
+ * );
+ * ```
+ */
+export function AuthProvider({
+ children,
+ loadingComponent = <DefaultLoadingComponent />,
+}: AuthProviderProps) {
+ const [isInitialized, setIsInitialized] = useState(false);
+ const [initError, setInitError] = useState<Error | null>(null);
+
+ useEffect(() => {
+ initializeMsal()
+ .then(() => setIsInitialized(true))
+ .catch((error) => {
+ console.error("Failed to initialize MSAL:", error);
+ setInitError(error);
+ });
+ }, []);
+
+ if (initError) {
+ return (
+ <div style={{ padding: "20px", color: "red" }}>
+ <h2>Authentication Error</h2>
+ <p>Failed to initialize authentication: {initError.message}</p>
+ <button onClick={() => window.location.reload()}>Retry</button>
+ </div>
+ );
+ }
+
+ if (!isInitialized) {
+ return <>{loadingComponent}</>;
+ }
+
+ return <MsalProvider instance={msalInstance}>{children}</MsalProvider>;
+}
+
+/**
+ * Default loading component shown during MSAL initialization
+ */
+function DefaultLoadingComponent() {
+ return (
+ <div
+ style={{
+ display: "flex",
+ justifyContent: "center",
+ alignItems: "center",
+ height: "100vh",
+ fontFamily: "system-ui, sans-serif",
+ }}
+ >
+ <div style={{ textAlign: "center" }}>
+ <div
+ style={{
+ width: "40px",
+ height: "40px",
+ border: "3px solid #f3f3f3",
+ borderTop: "3px solid #0078d4",
+ borderRadius: "50%",
+ animation: "spin 1s linear infinite",
+ margin: "0 auto 16px",
+ }}
+ />
+ <p style={{ color: "#666" }}>Initializing authentication...</p>
+ <style>{`
+ @keyframes spin {
+ 0% { transform: rotate(0deg); }
+ 100% { transform: rotate(360deg); }
+ }
+ `}</style>
+ </div>
+ </div>
+ );
+}
+
+/**
+ * Hook to check if MSAL is currently processing an interaction
+ * Useful to prevent calling interactive APIs while another is in progress
+ */
+export function useAuthInProgress(): boolean {
+ const { inProgress } = useMsal();
+ return inProgress !== InteractionStatus.None;
+}
diff --git a/skills/azure-auth/templates/protected-route.tsx b/skills/azure-auth/templates/protected-route.tsx
new file mode 100644
index 00000000..aceb69d9
--- /dev/null
+++ b/skills/azure-auth/templates/protected-route.tsx
@@ -0,0 +1,305 @@
+/**
+ * Protected Route Components for MSAL React
+ *
+ * Provides components to protect routes that require authentication.
+ * Handles loading states, authentication checks, and automatic login redirects.
+ */
+
+import React from "react";
+import {
+ useMsal,
+ useIsAuthenticated,
+ AuthenticatedTemplate,
+ UnauthenticatedTemplate,
+} from "@azure/msal-react";
+import { InteractionStatus } from "@azure/msal-browser";
+import { loginRequest } from "./msal-config";
+
+interface ProtectedRouteProps {
+ children: React.ReactNode;
+ /** Component to show while checking auth status */
+ loadingComponent?: React.ReactNode;
+ /** Component to show for unauthenticated users (instead of auto-redirect) */
+ fallback?: React.ReactNode;
+ /** If true, automatically redirect to login. If false, show fallback */
+ autoRedirect?: boolean;
+}
+
+/**
+ * Protected Route Component
+ *
+ * Wraps content that should only be visible to authenticated users.
+ * By default, automatically redirects unauthenticated users to login.
+ *
+ * Usage:
+ * ```tsx
+ * <ProtectedRoute>
+ * <DashboardPage />
+ * </ProtectedRoute>
+ * ```
+ *
+ * With custom fallback:
+ * ```tsx
+ * <ProtectedRoute
+ * autoRedirect={false}
+ * fallback={<LoginPrompt />}
+ * >
+ * <DashboardPage />
+ * </ProtectedRoute>
+ * ```
+ */
+export function ProtectedRoute({
+ children,
+ loadingComponent = <DefaultLoadingComponent />,
+ fallback,
+ autoRedirect = true,
+}: ProtectedRouteProps) {
+ const { instance, inProgress } = useMsal();
+ const isAuthenticated = useIsAuthenticated();
+
+ // Wait for MSAL to finish any in-progress operations
+ // This prevents race conditions with redirect handling
+ if (inProgress !== InteractionStatus.None) {
+ return <>{loadingComponent}</>;
+ }
+
+ // User is authenticated, render protected content
+ if (isAuthenticated) {
+ return <>{children}</>;
+ }
+
+ // User is not authenticated
+ if (autoRedirect) {
+ // Trigger login redirect
+ // Using loginRedirect instead of loginPopup for better mobile support
+ instance.loginRedirect(loginRequest).catch((error) => {
+ console.error("Login redirect failed:", error);
+ });
+
+ return <>{loadingComponent}</>;
+ }
+
+ // Show fallback for unauthenticated users
+ return <>{fallback || <DefaultUnauthenticatedComponent />}</>;
+}
+
+/**
+ * Alternative approach using MSAL's built-in templates
+ *
+ * This is simpler but less flexible than ProtectedRoute.
+ * Use for straightforward protected/public content switching.
+ *
+ * Usage:
+ * ```tsx
+ * <AuthenticatedContent fallback={<LoginButton />}>
+ * <UserProfile />
+ * </AuthenticatedContent>
+ * ```
+ */
+export function AuthenticatedContent({
+ children,
+ fallback,
+}: {
+ children: React.ReactNode;
+ fallback?: React.ReactNode;
+}) {
+ return (
+ <>
+ <AuthenticatedTemplate>{children}</AuthenticatedTemplate>
+ <UnauthenticatedTemplate>
+ {fallback || <DefaultUnauthenticatedComponent />}
+ </UnauthenticatedTemplate>
+ </>
+ );
+}
+
+/**
+ * Login Button Component
+ *
+ * Triggers login flow when clicked.
+ */
+export function LoginButton({
+ children = "Sign in with Microsoft",
+ className,
+ style,
+}: {
+ children?: React.ReactNode;
+ className?: string;
+ style?: React.CSSProperties;
+}) {
+ const { instance, inProgress } = useMsal();
+ const isLoading = inProgress !== InteractionStatus.None;
+
+ const handleLogin = () => {
+ if (isLoading) return;
+ instance.loginRedirect(loginRequest).catch((error) => {
+ console.error("Login failed:", error);
+ });
+ };
+
+ return (
+ <button
+ onClick={handleLogin}
+ disabled={isLoading}
+ className={className}
+ style={{
+ padding: "10px 20px",
+ backgroundColor: "#0078d4",
+ color: "white",
+ border: "none",
+ borderRadius: "4px",
+ cursor: isLoading ? "wait" : "pointer",
+ opacity: isLoading ? 0.7 : 1,
+ display: "inline-flex",
+ alignItems: "center",
+ gap: "8px",
+ fontFamily: "system-ui, sans-serif",
+ fontSize: "14px",
+ ...style,
+ }}
+ >
+ {/* Microsoft logo */}
+ <svg width="16" height="16" viewBox="0 0 21 21" fill="currentColor">
+ <rect x="1" y="1" width="9" height="9" />
+ <rect x="11" y="1" width="9" height="9" />
+ <rect x="1" y="11" width="9" height="9" />
+ <rect x="11" y="11" width="9" height="9" />
+ </svg>
+ {isLoading ? "Signing in..." : children}
+ </button>
+ );
+}
+
+/**
+ * Logout Button Component
+ */
+export function LogoutButton({
+ children = "Sign out",
+ className,
+ style,
+}: {
+ children?: React.ReactNode;
+ className?: string;
+ style?: React.CSSProperties;
+}) {
+ const { instance, inProgress } = useMsal();
+ const isLoading = inProgress !== InteractionStatus.None;
+
+ const handleLogout = () => {
+ if (isLoading) return;
+ instance.logoutRedirect().catch((error) => {
+ console.error("Logout failed:", error);
+ });
+ };
+
+ return (
+ <button
+ onClick={handleLogout}
+ disabled={isLoading}
+ className={className}
+ style={{
+ padding: "8px 16px",
+ backgroundColor: "transparent",
+ color: "#666",
+ border: "1px solid #ddd",
+ borderRadius: "4px",
+ cursor: isLoading ? "wait" : "pointer",
+ fontFamily: "system-ui, sans-serif",
+ fontSize: "14px",
+ ...style,
+ }}
+ >
+ {isLoading ? "Signing out..." : children}
+ </button>
+ );
+}
+
+/**
+ * User Info Component
+ *
+ * Displays the currently signed-in user's information.
+ */
+export function UserInfo() {
+ const { accounts } = useMsal();
+ const account = accounts[0];
+
+ if (!account) {
+ return null;
+ }
+
+ return (
+ <div
+ style={{
+ display: "flex",
+ alignItems: "center",
+ gap: "12px",
+ fontFamily: "system-ui, sans-serif",
+ }}
+ >
+ <div
+ style={{
+ width: "32px",
+ height: "32px",
+ borderRadius: "50%",
+ backgroundColor: "#0078d4",
+ color: "white",
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ fontSize: "14px",
+ fontWeight: 500,
+ }}
+ >
+ {account.name?.charAt(0).toUpperCase() || "U"}
+ </div>
+ <div>
+ <div style={{ fontWeight: 500 }}>{account.name}</div>
+ <div style={{ fontSize: "12px", color: "#666" }}>
+ {account.username}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+// Default components
+function DefaultLoadingComponent() {
+ return (
+ <div
+ style={{
+ display: "flex",
+ justifyContent: "center",
+ alignItems: "center",
+ height: "100%",
+ minHeight: "200px",
+ }}
+ >
+ <p style={{ color: "#666", fontFamily: "system-ui, sans-serif" }}>
+ Loading...
+ </p>
+ </div>
+ );
+}
+
+function DefaultUnauthenticatedComponent() {
+ return (
+ <div
+ style={{
+ display: "flex",
+ flexDirection: "column",
+ alignItems: "center",
+ justifyContent: "center",
+ height: "100%",
+ minHeight: "300px",
+ gap: "16px",
+ fontFamily: "system-ui, sans-serif",
+ }}
+ >
+ <h2 style={{ margin: 0 }}>Sign in required</h2>
+ <p style={{ color: "#666", margin: 0 }}>
+ Please sign in to access this content.
+ </p>
+ <LoginButton />
+ </div>
+ );
+}
diff --git a/skills/azure-auth/templates/use-api-token.ts b/skills/azure-auth/templates/use-api-token.ts
new file mode 100644
index 00000000..5f58dcd2
--- /dev/null
+++ b/skills/azure-auth/templates/use-api-token.ts
@@ -0,0 +1,234 @@
+/**
+ * React Hook for Acquiring API Tokens
+ *
+ * Provides a hook to safely acquire access tokens for calling your backend API.
+ * Handles silent token acquisition with automatic fallback to interactive login
+ * when tokens expire or need consent.
+ */
+
+import { useMsal } from "@azure/msal-react";
+import {
+ InteractionRequiredAuthError,
+ SilentRequest,
+} from "@azure/msal-browser";
+import { useCallback, useState } from "react";
+import { apiRequest } from "./msal-config";
+
+interface UseApiTokenResult {
+ /** Get an access token for API calls */
+ getAccessToken: () => Promise<string | null>;
+ /** Whether a token acquisition is in progress */
+ isLoading: boolean;
+ /** Any error that occurred during token acquisition */
+ error: Error | null;
+ /** Clear any stored error */
+ clearError: () => void;
+}
+
+/**
+ * Hook for acquiring access tokens for API calls.
+ *
+ * Usage:
+ * ```tsx
+ * function ApiComponent() {
+ * const { getAccessToken, isLoading, error } = useApiToken();
+ *
+ * async function fetchData() {
+ * const token = await getAccessToken();
+ * if (!token) return;
+ *
+ * const response = await fetch("/api/data", {
+ * headers: {
+ * Authorization: `Bearer ${token}`,
+ * },
+ * });
+ * // handle response...
+ * }
+ *
+ * return (
+ * <button onClick={fetchData} disabled={isLoading}>
+ * {isLoading ? "Loading..." : "Fetch Data"}
+ * </button>
+ * );
+ * }
+ * ```
+ */
+export function useApiToken(): UseApiTokenResult {
+ const { instance, accounts } = useMsal();
+ const [isLoading, setIsLoading] = useState(false);
+ const [error, setError] = useState<Error | null>(null);
+
+ const getAccessToken = useCallback(async (): Promise<string | null> => {
+ // Check if user is signed in
+ if (accounts.length === 0) {
+ setError(new Error("No user signed in"));
+ return null;
+ }
+
+ setIsLoading(true);
+ setError(null);
+
+ const request: SilentRequest = {
+ ...apiRequest,
+ account: accounts[0],
+ };
+
+ try {
+ // Try silent token acquisition first
+ // This uses cached tokens or refresh tokens
+ const response = await instance.acquireTokenSilent(request);
+ return response.accessToken;
+ } catch (err) {
+ // Handle interaction required errors
+ // These occur when:
+ // - Refresh token expired (AADSTS700084 - 24hr limit for SPAs)
+ // - Consent needed for new scopes
+ // - MFA required
+ // - Password changed
+ if (err instanceof InteractionRequiredAuthError) {
+ try {
+ // Fall back to interactive login
+ // Using redirect instead of popup for better mobile support
+ await instance.acquireTokenRedirect(request);
+ // This will redirect, so we won't reach here
+ return null;
+ } catch (redirectError) {
+ const error = new Error(
+ `Interactive login failed: ${redirectError}`
+ );
+ setError(error);
+ return null;
+ }
+ }
+
+ // Other errors (network, configuration, etc.)
+ const error =
+ err instanceof Error ? err : new Error("Failed to acquire token");
+ setError(error);
+ return null;
+ } finally {
+ setIsLoading(false);
+ }
+ }, [instance, accounts]);
+
+ const clearError = useCallback(() => {
+ setError(null);
+ }, []);
+
+ return {
+ getAccessToken,
+ isLoading,
+ error,
+ clearError,
+ };
+}
+
+/**
+ * Higher-order function to create an authenticated fetch wrapper.
+ *
+ * Usage:
+ * ```tsx
+ * function MyComponent() {
+ * const { getAccessToken } = useApiToken();
+ * const authFetch = useAuthenticatedFetch(getAccessToken);
+ *
+ * async function loadData() {
+ * const response = await authFetch("/api/data");
+ * const data = await response.json();
+ * }
+ * }
+ * ```
+ */
+export function useAuthenticatedFetch(
+ getAccessToken: () => Promise<string | null>
+) {
+ return useCallback(
+ async (url: string, options: RequestInit = {}): Promise<Response> => {
+ const token = await getAccessToken();
+
+ if (!token) {
+ throw new Error("Failed to acquire access token");
+ }
+
+ const headers = new Headers(options.headers);
+ headers.set("Authorization", `Bearer ${token}`);
+
+ return fetch(url, {
+ ...options,
+ headers,
+ });
+ },
+ [getAccessToken]
+ );
+}
+
+/**
+ * Hook for making authenticated API calls with automatic token handling.
+ *
+ * Usage:
+ * ```tsx
+ * function DataComponent() {
+ * const { data, isLoading, error, refetch } = useAuthenticatedQuery<User[]>(
+ * "/api/users"
+ * );
+ *
+ * if (isLoading) return <Loading />;
+ * if (error) return <Error message={error.message} />;
+ *
+ * return <UserList users={data} />;
+ * }
+ * ```
+ */
+export function useAuthenticatedQuery<T>(
+ url: string,
+ options?: RequestInit
+): {
+ data: T | null;
+ isLoading: boolean;
+ error: Error | null;
+ refetch: () => void;
+} {
+ const { getAccessToken } = useApiToken();
+ const [data, setData] = useState<T | null>(null);
+ const [isLoading, setIsLoading] = useState(false);
+ const [error, setError] = useState<Error | null>(null);
+ const [fetchTrigger, setFetchTrigger] = useState(0);
+
+ const refetch = useCallback(() => {
+ setFetchTrigger((prev) => prev + 1);
+ }, []);
+
+ // Fetch data when component mounts or refetch is called
+ useCallback(async () => {
+ setIsLoading(true);
+ setError(null);
+
+ try {
+ const token = await getAccessToken();
+ if (!token) {
+ throw new Error("Failed to acquire access token");
+ }
+
+ const headers = new Headers(options?.headers);
+ headers.set("Authorization", `Bearer ${token}`);
+
+ const response = await fetch(url, {
+ ...options,
+ headers,
+ });
+
+ if (!response.ok) {
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
+ }
+
+ const result = (await response.json()) as T;
+ setData(result);
+ } catch (err) {
+ setError(err instanceof Error ? err : new Error("Failed to fetch data"));
+ } finally {
+ setIsLoading(false);
+ }
+ }, [url, options, getAccessToken, fetchTrigger]);
+
+ return { data, isLoading, error, refetch };
+}
diff --git a/skills/azure-auth/templates/workers-jwt-validation.ts b/skills/azure-auth/templates/workers-jwt-validation.ts
new file mode 100644
index 00000000..0c04dab8
--- /dev/null
+++ b/skills/azure-auth/templates/workers-jwt-validation.ts
@@ -0,0 +1,306 @@
+/**
+ * Microsoft Entra ID JWT Validation for Cloudflare Workers
+ *
+ * IMPORTANT: MSAL.js does NOT work in Cloudflare Workers because it relies on
+ * browser/Node.js APIs. Use the jose library for token validation instead.
+ *
+ * This module provides:
+ * - JWT validation using Azure AD's public keys (JWKS)
+ * - Proper JWKS endpoint discovery (Azure uses non-standard path)
+ * - Caching to avoid fetching keys on every request
+ * - Multi-tenant support
+ */
+
+import * as jose from "jose";
+
+/**
+ * Decoded token payload from Microsoft Entra ID
+ */
+export interface EntraTokenPayload {
+ /** Audience - your application's client ID or API URI */
+ aud: string;
+ /** Issuer - https://login.microsoftonline.com/{tenant}/v2.0 */
+ iss: string;
+ /** Subject - unique identifier for the user */
+ sub: string;
+ /** Object ID - user's Azure AD object ID */
+ oid: string;
+ /** Tenant ID - the Azure AD tenant */
+ tid: string;
+ /** User's email (may be preferred_username) */
+ preferred_username: string;
+ /** Display name */
+ name: string;
+ /** Email address (if available) */
+ email?: string;
+ /** App roles assigned to the user */
+ roles?: string[];
+ /** Scopes granted (space-separated string) */
+ scp?: string;
+ /** Issued at timestamp */
+ iat: number;
+ /** Expiration timestamp */
+ exp: number;
+ /** Not before timestamp */
+ nbf: number;
+}
+
+/**
+ * Environment bindings required for token validation
+ */
+export interface AuthEnv {
+ /** Azure AD tenant ID (GUID) */
+ AZURE_TENANT_ID: string;
+ /** Azure AD application (client) ID (GUID) */
+ AZURE_CLIENT_ID: string;
+}
+
+// JWKS cache to avoid fetching on every request
+interface JWKSCache {
+ jwks: jose.JWTVerifyGetKey;
+ fetchedAt: number;
+}
+
+const jwksCache = new Map<string, JWKSCache>();
+const JWKS_CACHE_DURATION = 3600000; // 1 hour in milliseconds
+
+/**
+ * Fetches the JWKS for a given Azure AD tenant.
+ *
+ * CRITICAL: Azure AD does NOT serve JWKS at the standard
+ * .well-known/jwks.json path. You must first fetch the
+ * OpenID configuration to get the correct jwks_uri.
+ */
+async function getJWKS(tenantId: string): Promise<jose.JWTVerifyGetKey> {
+ const now = Date.now();
+ const cached = jwksCache.get(tenantId);
+
+ // Return cached JWKS if still valid
+ if (cached && now - cached.fetchedAt < JWKS_CACHE_DURATION) {
+ return cached.jwks;
+ }
+
+ // Fetch OpenID configuration to get JWKS URI
+ // This is the CORRECT way to discover Azure AD's JWKS endpoint
+ const configUrl = `https://login.microsoftonline.com/${tenantId}/v2.0/.well-known/openid-configuration`;
+
+ const configResponse = await fetch(configUrl);
+ if (!configResponse.ok) {
+ throw new Error(
+ `Failed to fetch OpenID configuration: ${configResponse.status}`
+ );
+ }
+
+ const config = (await configResponse.json()) as { jwks_uri: string };
+
+ // Create remote JWKS using the discovered URI
+ const jwks = jose.createRemoteJWKSet(new URL(config.jwks_uri));
+
+ // Cache for future requests
+ jwksCache.set(tenantId, { jwks, fetchedAt: now });
+
+ return jwks;
+}
+
+/**
+ * Validates a Microsoft Entra ID JWT token.
+ *
+ * @param token - The JWT token (without "Bearer " prefix)
+ * @param env - Environment bindings with Azure configuration
+ * @returns Decoded token payload if valid, null if invalid
+ *
+ * Usage:
+ * ```typescript
+ * const authHeader = request.headers.get("Authorization");
+ * if (!authHeader?.startsWith("Bearer ")) {
+ * return new Response("Unauthorized", { status: 401 });
+ * }
+ *
+ * const token = authHeader.slice(7);
+ * const user = await validateEntraToken(token, env);
+ *
+ * if (!user) {
+ * return new Response("Invalid token", { status: 401 });
+ * }
+ *
+ * // Token is valid, user contains the decoded claims
+ * console.log(`User: ${user.name} (${user.preferred_username})`);
+ * ```
+ */
+export async function validateEntraToken(
+ token: string,
+ env: AuthEnv
+): Promise<EntraTokenPayload | null> {
+ try {
+ const jwks = await getJWKS(env.AZURE_TENANT_ID);
+
+ const { payload } = await jose.jwtVerify(token, jwks, {
+ // Validate issuer matches expected tenant
+ issuer: `https://login.microsoftonline.com/${env.AZURE_TENANT_ID}/v2.0`,
+
+ // Validate audience matches your application
+ // Can be client ID or API URI (api://{client_id})
+ audience: env.AZURE_CLIENT_ID,
+ });
+
+ return payload as unknown as EntraTokenPayload;
+ } catch (error) {
+ // Log error details for debugging (avoid in production)
+ if (error instanceof jose.errors.JWTExpired) {
+ console.warn("Token expired");
+ } else if (error instanceof jose.errors.JWTClaimValidationFailed) {
+ console.warn("Token claim validation failed:", error.message);
+ } else {
+ console.error("Token validation error:", error);
+ }
+
+ return null;
+ }
+}
+
+/**
+ * Validates a token for multi-tenant applications.
+ *
+ * For multi-tenant apps, the issuer varies based on the user's tenant.
+ * This function extracts the tenant from the token and validates accordingly.
+ *
+ * @param token - The JWT token (without "Bearer " prefix)
+ * @param clientId - Your application's client ID
+ * @returns Decoded token payload if valid, null if invalid
+ */
+export async function validateMultiTenantToken(
+ token: string,
+ clientId: string
+): Promise<EntraTokenPayload | null> {
+ try {
+ // First, decode without verification to get the tenant ID
+ const decoded = jose.decodeJwt(token);
+ const tenantId = decoded.tid as string;
+
+ if (!tenantId) {
+ console.warn("Token missing tenant ID (tid) claim");
+ return null;
+ }
+
+ // Now validate with the correct tenant's JWKS
+ const jwks = await getJWKS(tenantId);
+
+ const { payload } = await jose.jwtVerify(token, jwks, {
+ issuer: `https://login.microsoftonline.com/${tenantId}/v2.0`,
+ audience: clientId,
+ });
+
+ return payload as unknown as EntraTokenPayload;
+ } catch (error) {
+ console.error("Multi-tenant token validation error:", error);
+ return null;
+ }
+}
+
+/**
+ * Middleware pattern for Cloudflare Workers
+ *
+ * Usage:
+ * ```typescript
+ * export default {
+ * async fetch(request: Request, env: Env): Promise<Response> {
+ * // Public routes
+ * const url = new URL(request.url);
+ * if (url.pathname === "/" || url.pathname.startsWith("/public")) {
+ * return handlePublicRoute(request, env);
+ * }
+ *
+ * // Protected routes
+ * const authResult = await requireAuth(request, env);
+ * if (authResult instanceof Response) {
+ * return authResult; // 401 response
+ * }
+ *
+ * // authResult is the validated user
+ * return handleProtectedRoute(request, env, authResult);
+ * },
+ * };
+ * ```
+ */
+export async function requireAuth(
+ request: Request,
+ env: AuthEnv
+): Promise<EntraTokenPayload | Response> {
+ const authHeader = request.headers.get("Authorization");
+
+ if (!authHeader) {
+ return new Response(
+ JSON.stringify({ error: "Missing Authorization header" }),
+ {
+ status: 401,
+ headers: {
+ "Content-Type": "application/json",
+ "WWW-Authenticate": 'Bearer realm="api"',
+ },
+ }
+ );
+ }
+
+ if (!authHeader.startsWith("Bearer ")) {
+ return new Response(
+ JSON.stringify({ error: "Invalid Authorization header format" }),
+ {
+ 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 or expired token" }), {
+ status: 401,
+ headers: { "Content-Type": "application/json" },
+ });
+ }
+
+ return user;
+}
+
+/**
+ * Check if user has specific roles.
+ *
+ * App roles must be configured in Azure Portal:
+ * App Registration > App roles > Create app role
+ *
+ * Then assign users/groups to roles:
+ * Enterprise applications > Your app > Users and groups
+ */
+export function hasRole(
+ user: EntraTokenPayload,
+ requiredRole: string
+): boolean {
+ return user.roles?.includes(requiredRole) ?? false;
+}
+
+/**
+ * Check if user has any of the specified roles.
+ */
+export function hasAnyRole(
+ user: EntraTokenPayload,
+ roles: string[]
+): boolean {
+ if (!user.roles) return false;
+ return roles.some((role) => user.roles!.includes(role));
+}
+
+/**
+ * Check if token has specific scopes.
+ *
+ * Scopes are space-separated in the scp claim.
+ */
+export function hasScope(
+ user: EntraTokenPayload,
+ requiredScope: string
+): boolean {
+ if (!user.scp) return false;
+ const scopes = user.scp.split(" ");
+ return scopes.includes(requiredScope);
+}