#atom

Setting up Microsoft Authentication Library for React applications

Core Idea: Proper MSAL configuration is essential for secure and effective Azure AD authentication in React applications, with settings that control authentication behavior, caching, and logging.

Key Elements

Core Configuration Structure

// authConfig.js
import { LogLevel } from "@azure/msal-browser";

export const msalConfig = {
  auth: {
    clientId: "your-client-id",           // Application ID from Azure portal
    authority: "https://login.microsoftonline.com/your-tenant-id", // Tenant-specific authority
    redirectUri: "https://your-app.com/auth",  // Registered redirect URI
    postLogoutRedirectUri: "https://your-app.com/" // Redirect after logout
  },
  cache: {
    cacheLocation: "sessionStorage",      // localStorage or sessionStorage
    storeAuthStateInCookie: false         // Needed for IE11
  },
  system: {
    loggerOptions: {
      loggerCallback: (level, message, containsPii) => {
        if (containsPii) return;
        switch (level) {
          case LogLevel.Error:
            console.error(message);
            break;
          case LogLevel.Warning:
            console.warn(message);
            break;
          case LogLevel.Info:
            console.info(message);
            break;
        }
      },
      logLevel: LogLevel.Info
    }
  }
};

Authentication Request Configuration

export const loginRequest = {
  scopes: ["User.Read", "GroupMember.Read.All"]
};

export const graphConfig = {
  graphMeEndpoint: "https://graph.microsoft.com/v1.0/me"
};

Environment Configuration Management

// getEnvVars.js
const getEnvVars = () => {
  return {
    REACT_APP_AUTH_CLIENT_ID: process.env.REACT_APP_AUTH_CLIENT_ID,
    REACT_APP_AUTH_AUTHORITY: process.env.REACT_APP_AUTH_AUTHORITY,
    REACT_APP_AUTH_REDIRECT_URI: process.env.REACT_APP_AUTH_REDIRECT_URI,
    REACT_APP_AUTH_GRAPHME_ENDPOINT: process.env.REACT_APP_AUTH_GRAPHME_ENDPOINT,
    REACT_APP_REQUIRED_GROUP: process.env.REACT_APP_REQUIRED_GROUP
  };
};

export default getEnvVars;

MSAL Initialization

// index.jsx or App.jsx
import { PublicClientApplication } from "@azure/msal-browser";
import { MsalProvider } from "@azure/msal-react";
import { msalConfig } from "./authConfig";

const msalInstance = new PublicClientApplication(msalConfig);

ReactDOM.render(
  <MsalProvider instance={msalInstance}>
    <App />
  </MsalProvider>,
  document.getElementById("root")
);

Additional Connections

References

  1. MSAL.js configuration documentation
  2. Azure AD authentication best practices

#msal #configuration #azure #authentication #react


Connections:


Sources: