#atom

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

// 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

// 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

// 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

Additional Connections

References

  1. MSAL React documentation
  2. React Context API documentation

#msal #react #authentication #provider-pattern #context-api


Connections:


Sources: