LeoYeAI/agent-master-skills / skills/azure-auth
azure-auth
VerifiedMicrosoft 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.
| File | Kind | Size |
|---|---|---|
| .claude-plugin/plugin.json | config | 688 B |
| README.md | markdown | 2.5 KB |
| SKILL.md | skill md | 19.7 KB |
| _meta.json | config | 284 B |
| references/aadsts-error-codes.md | markdown | 7.7 KB |
| rules/azure-auth.md | markdown | 3.4 KB |
| templates/msal-config.ts | script | 2.9 KB |
| templates/msal-provider.tsx | other | 4.5 KB |
| templates/protected-route.tsx | other | 7.1 KB |
| templates/use-api-token.ts | script | 6.0 KB |
| templates/workers-jwt-validation.ts | script | 8.3 KB |
templates/msal-provider.tsx
View on GitHub/**
* 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;
}
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| writing-skillsobra/superpowersUse when creating new skills, editing existing skills, or verifying skills work before deployment | Stars: 323k | Updated | Claude CodeCodex | Verified | Install |
| xlsxanthropics/skillsUse this skill any time a spreadsheet file is the primary input or output. This means any task where the user wants to: open, read, edit, or fix an existing .xlsx, .xlsm, .xltx, .csv, or .tsv file (e.g., adding columns, computing formulas, formatting, charting, cleaning messy data); create a new spreadsheet from scratch or from other data sources; or convert between tabular file formats. Trigger especially when the user references a spreadsheet file by name or path — even casually (like "the xlsx in my downloads") — and wants something done to it or produced from it. Also trigger for cleaning or restructuring messy tabular data files (malformed rows, misplaced headers, junk data) into proper spreadsheets. The deliverable must be a spreadsheet file. Do NOT trigger when the primary deliverable is a Word document, HTML report, standalone Python script, database pipeline, or Google Sheets API integration, even if tabular data is involved. | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |
| shipping-and-launchaddyosmani/agent-skillsPrepares production launches. Use when preparing to deploy to production, or when asking what needs to be in place before shipping. Use when you need a pre-launch checklist, when setting up monitoring, when planning a staged rollout, or when you need a rollback strategy. | Stars: 119k | Updated | Claude CodeCodex | Verified | Install |
| childhoodthedotmack/claude-memBabysit a shipped release after merge, publication, or deployment. Verify published packages, production behavior, installed plugins, and late CI or user reports until the observation window is clean; use babysit for PR readiness before release. | Stars: 118k | Updated | Claude CodeCodex | Verified | Install |