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

a simple example for jdbc PreparedStatement

a simple example for PreparedStatement package basics.in.java.blogspot.in; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class Main { private static final String USERNAME="root"; private static final String PASSWORD=""; private static final String CONN_STRING="jdbc:mysql://localhost/basicsinjavablogspot"; public static void main(String[] args) throws ClassNotFoundException, SQLException { Class.forName("com.mysql.jdbc.Driver"); Connection conn=null; Statement stmt=null; ResultSet rs=null; try { conn= DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD); System.out.println("database connection successful"); //stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); String sql="select * fr...

Server-Side Pagination with React-Table and Spring Boot JPA with H2 Database

Pagination is a common technique used to split large amounts of data into smaller, more manageable chunks. With server-side pagination, data is retrieved from the server in smaller batches, reducing the amount of data transferred over the network and improving application performance. React-Table provides a wide range of built-in features such as sorting, filtering, pagination, row selection, and column resizing. These features can be easily configured and customized to fit specific requirements. For example, you can customize the sorting behavior to handle multiple sorting criteria, or you can add custom filters to the table to handle complex data filtering scenarios. Additionally, React-Table provides a flexible API that allows developers to extend its functionality with custom hooks, plugins, and components. This means that you can easily add custom functionality to the table, such as exporting data to CSV or integrating with external data sources. In terms of styl...