Configuring the authentication context for React components
Core Idea: The MSAL Provider pattern creates an authentication context that makes MSAL functionality available throughout a React component tree, enabling components to access authentication state and methods.
Key Elements
Provider Setup
- Wraps the application or a section of components
- Initializes and provides access to the MSAL instance
- Creates context for authentication-related hooks
// App.jsx - MSAL Provider Setup
import { PublicClientApplication } from "@azure/msal-browser";
import { MsalProvider } from "@azure/msal-react";
import { msalConfig } from "./authConfig";
import { useState, useEffect } from "react";
import { BrowserRouter as Router } from "react-router-dom";
const msalInstance = new PublicClientApplication(msalConfig);
function App() {
const [isInitialized, setIsInitialized] = useState(false);
useEffect(() => {
msalInstance.initialize().then(() => {
setIsInitialized(true);
});
}, []);
if (!isInitialized) {
return <div>Loading...</div>;
}
return (
<MsalProvider instance={msalInstance}>
<Router>
{/* Application routes and components */}
</Router>
</MsalProvider>
);
}
Component Integration
- Enables authentication hooks throughout the application
- Allows components to access account information
- Provides authentication state across component boundaries
// Protected component example
import { useMsal, useIsAuthenticated } from "@azure/msal-react";
function Profile() {
const { accounts } = useMsal();
const isAuthenticated = useIsAuthenticated();
if (!isAuthenticated) {
return <div>Please sign in</div>;
}
const userName = accounts[0]?.name || "Unknown User";
return <div>Welcome, {userName}!</div>;
}
Authentication Components
AuthenticatedTemplate: Renders content only when user is authenticatedUnauthenticatedTemplate: Renders content only when user is not authenticated- These components rely on the MsalProvider context
// Using authentication templates
import {
AuthenticatedTemplate,
UnauthenticatedTemplate
} from "@azure/msal-react";
function HomePage() {
return (
<div>
<h1>Welcome to Our App</h1>
<AuthenticatedTemplate>
<ProfileContent />
<SignOutButton />
</AuthenticatedTemplate>
<UnauthenticatedTemplate>
<p>Please sign in to access your profile.</p>
<SignInButton />
</UnauthenticatedTemplate>
</div>
);
}
Initialization Handling
- Ensuring MSAL is initialized before rendering
- Loading states during initialization
- Error handling for initialization failures
Additional Connections
- Broader Context: React Context API (pattern used by MSAL Provider)
- Applications: Protected Routes with MSAL React (using the provider)
- See Also: MSAL React Hooks (hooks that rely on the provider)
References
- MSAL React documentation
- React Context API documentation
#msal #react #authentication #provider-pattern #context-api
Connections:
Sources: