Skip to main content

Integrating Azure AD with React.js Using @azure/msal-browser 2.15.0 and @azure/msal-react 1.0.1

In this blog post, we will explore how to integrate Azure AD with a React.js application using the @azure/msal-browser and @azure/msal-react libraries.

Prerequisites

  • Node.js and npm installed on your machine
  • React.js project set up (create-react-app or similar)
  • Azure AD tenant and registered application

Step 1: Install Dependencies

Start by navigating to your React.js project directory and install the required dependencies:

$ npm install @azure/msal-browser@2.15.0 @azure/msal-react@1.0.1
  

Step 2: Configure Azure AD

Next, you need to configure your Azure AD tenant and registered application. Follow these steps:

  1. Sign in to the Azure portal and navigate to the Azure Active Directory section.
  2. Under the "App registrations" tab, select your registered application or create a new one.
  3. Make note of the "Application (client) ID" as you'll need it later.
  4. Under the "Authentication" section, add the redirect URIs for your React.js application. For development, it could be http://localhost:3000.
  5. Generate a client secret or create a public client for your application based on your requirements.
  6. Make note of the Azure AD tenant ID as well.

Step 3: Implement Authentication

Now, let's integrate Azure AD authentication into your React.js application. Create a new file called AuthConfig.js and add the following code:

// AuthConfig.js
export const msalConfig = {
  auth: {
    clientId: 'YOUR_CLIENT_ID',
    authority: 'https://login.microsoftonline.com/YOUR_TENANT_ID',
    redirectUri: 'http://localhost:3000',
  }
};
  

Replace YOUR_CLIENT_ID and YOUR_TENANT_ID with your Azure AD application's client ID and tenant ID.

Next, create a new file called AuthContext.js and add the following code:

// AuthContext.js
import { PublicClientApplication } from '@azure/msal-browser';

export const msalInstance = new PublicClientApplication({
  auth: {
    clientId: 'YOUR_CLIENT_ID',
    authority: 'https://login.microsoftonline.com/YOUR_TENANT_ID',
    redirectUri: 'http://localhost:3000',
  }
});
  

Again, replace YOUR_CLIENT_ID and YOUR_TENANT_ID with your Azure AD application's client ID and tenant ID.

Step 4: Use Authentication in React Components

Now, you can use the authentication in your React components. Import the necessary hooks and components:

// App.js
import { MsalProvider, useMsal } from '@azure/msal-react';
import { msalConfig } from './AuthConfig';

function App() {
  return (
    <MsalProvider instance={msalInstance}>
      <AuthButton />
    </MsalProvider>
  );
}

function AuthButton() {
  const { instance } = useMsal();

  const handleLogin = async () => {
    try {
      await instance.loginPopup();
    } catch (error) {
      console.log('Login failed', error);
    }
  };

  const handleLogout = async () => {
    try {
      await instance.logoutPopup();
    } catch (error) {
      console.log('Logout failed', error);
    }
  };

  return (
    <div>
      <button onClick={handleLogin}>Login</button>
      <button onClick={handleLogout}>Logout</button>
    </div>
  );
}
  

In the above code, we wrap the main component (<App />) with the MsalProvider component and pass the msalInstance as the instance prop.

The AuthButton component demonstrates how to use the authentication functionality provided by @azure/msal-react package. The handleLogin function triggers the login popup, and the handleLogout function triggers the logout popup.

Step 5: Test the Integration

You can now test the Azure AD integration by running your React.js application and interacting with the authentication buttons.

$ npm start
  

If everything is configured correctly, you should be able to log in and log out using your Azure AD credentials.

Conclusion

In this blog post, we learned how to integrate Azure AD authentication into a React.js application using the @azure/msal-browser and @azure/msal-react libraries. We covered the installation, configuration, and usage of the libraries to enable user authentication with Azure AD.

Remember to secure your client secrets and other sensitive information when deploying your application to production.

sample repo: https://github.com/Azure-Samples/ms-identity-javascript-react-spa

Comments

Popular posts from this blog

Configuring Multiple Profiles in a Single YAML File for Spring Boot Application

Spring Boot provides a convenient way to configure application properties using YAML files. In a typical scenario, you might have different configurations for different environments such as development, testing, and production. Instead of maintaining multiple YAML files for each profile, you can configure multiple profiles within a single YAML file. This approach simplifies the configuration management process. Let's see how to achieve this. Step 1: Create a YAML Configuration File First, create a YAML file (e.g., application.yml ) in your Spring Boot project's resource directory. This file will contain the configuration properties for all the profiles you want to define. spring: profiles: active: dev logging: level: root: INFO com.example: DEBUG # Configuration for the 'dev' profile --- spring: profiles: dev database: url: jdbc:mysql://localhost:3306/devdb username: devuser password: devpassword # Co...

How to Open a Project in IntelliJ IDEA from the Command Line: A Step-by-Step Guide

How to Open a Project in IntelliJ IDEA from the Command Line IntelliJ IDEA is a popular and powerful Integrated Development Environment (IDE) for Java development. You may have a project folder that you want to open in IntelliJ IDEA. In this tutorial, we will walk through the steps for opening a project in IntelliJ IDEA from the command line. Configure IntelliJ IDEA for Command Line Use Before we can open a project in IntelliJ IDEA from the command line, we need to make sure that it is properly configured. Here are the steps: Open IntelliJ IDEA and go to Tools > Create Command-line Launcher . Select the installation path and click OK . Make sure that the launcher is added to your system PATH variable. You can do this by opening a terminal or command prompt and typing: which idea If the output is the path to the IntelliJ IDEA launcher, then you're good to go! Open a Project in IntelliJ IDEA from the Command Line Open your terminal or command prompt. ...

A End to End ant Build xml snippet

A End to End ant Build xml snippet you could use for reference <?xml version="1.0" encoding="UTF-8"?> <project name="End to End Build" default="sendmail" basedir=".">     <target name="init">         <tstamp />         <property file="build.properties" />             <path id="classpath">             <pathelement path="${servlet.jar}" />             <pathelement path="${junit.jar}" />         </path>