Secure your React.Js web application with Azure AD authentication using MASL Library.
Introduction
Welcome, fellow developers, to our journey into the world of securing React.js web applications using Azure AD authentication with the MSAL library.
In today’s digital landscape, where data breaches and security threats loom large, safeguarding our web applications has become paramount. Whether you’re building a personal blog, a business tool, or a social media platform, ensuring that only authorized users can access your application is crucial for protecting sensitive information and maintaining trust with your users.
This is where Azure Active Directory (AD) and the Microsoft Authentication Library (MSAL) come into play. Azure AD provides a robust and scalable identity management solution, while MSAL offers a streamlined way to integrate authentication into our React.js applications.
But why Azure AD, you might ask? Well, besides being a trusted and widely used identity provider, Azure AD offers a plethora of features that make it an attractive choice for securing our applications. From single sign-on (SSO) capabilities to multi-factor authentication (MFA) support, Azure AD equips us with the tools we need to enhance the security of our applications without reinventing the wheel.
In this blog post, we’ll dive into the nitty-gritty of setting up Azure AD authentication in our React.js applications using the MSAL library. We’ll cover everything from registering our application in Azure AD to implementing authentication flows in our React.js codebase. By the end of this journey, you’ll have the knowledge and tools you need to fortify your React.js applications against unauthorized access and keep your users’ data safe and sound.
So, grab your favorite beverage, fire up your code editor, and let’s embark on this adventure together as we explore the exciting world of securing React.js web applications with Azure AD authentication using MSAL. Let’s get started!
Background Information and Requirements
Before we dive headfirst into securing our React.js web application with Azure AD authentication using the MSAL library, let’s take a moment to understand the fundamentals and what we’ll need for this journey.
Understanding React.js and Azure AD
React.js: React.js has become the go-to JavaScript library for building user interfaces, known for its simplicity, reusability, and performance. Whether you’re building a small personal project or a large-scale enterprise application, React.js provides the tools you need to create dynamic and interactive user experiences.
Azure Active Directory (AD): Azure AD is Microsoft’s cloud-based identity and access management service, designed to help organizations manage user identities and control access to resources. With Azure AD, you can implement authentication and authorization mechanisms to protect your applications and data from unauthorized access.
Why Azure AD Authentication?
Robust Security: Azure AD offers enterprise-grade security features, including multi-factor authentication (MFA), conditional access policies, and identity protection, to help protect your applications and data from security threats.
Single Sign-On (SSO): Azure AD enables seamless single sign-on experiences for users, allowing them to access multiple applications with a single set of credentials, improving usability and productivity.
Scalability and Reliability: Azure AD is built on Microsoft’s global infrastructure, ensuring high availability, scalability, and reliability for your authentication and authorization needs.
Requirements
Before we proceed, let’s make sure we have everything we need:
Azure Account: You’ll need an Azure account to create an Azure AD tenant and register your application. You can sign up for a free Azure account if you don’t have one already.
React.js Application: We’ll be working with a React.js application, so make sure you have a basic understanding of React.js and have a project set up.
MSAL Library: We’ll be using the Microsoft Authentication Library (MSAL) to integrate Azure AD authentication into our React.js application. You can install the MSAL library using npm or yarn.
Access to Azure AD Tenant: You’ll need access to an Azure AD tenant to register your application and configure authentication settings. If you don’t have access to an Azure AD tenant, you can create one in the Azure portal.
Now that we have a good understanding of the background and requirements, let’s roll up our sleeves and start securing our React.js application with Azure AD authentication using the MSAL library. Let’s do this!
Setting Up Azure Active Directory (Azure AD)
To kickstart our journey towards securing our React.js web application with Azure AD authentication using the MSAL library, we first need to set up Azure Active Directory (Azure AD) and register our application. This process involves creating an Azure AD tenant, registering our application, and configuring authentication settings. Let’s dive in!
Step 1: Create an Azure Account (If you haven’t already)
If you don’t have an Azure account yet, you can sign up for a free account here. Once you have an account, sign in to the Azure portal.
Step 2: Create an Azure AD Tenant
Step 1: In the Azure portal, navigate to “Home” and go to create resource.
Step 2: Then search for “Azure AD B2C” and select the Azure Active Director B2C from the search results. Create Azure Active Directory B2C Resource
Step 3: Now you have to create an Azure AD tenant.
Step 4: Once the tenant is created, navigate to “Portal settings” and switch your Directory to the created directory.
Step 3: Register Your Application in Azure AD
Step 1: Now you should navigate to Microsoft Entra ID ( Previously it was called Azure AD ).
Step 2: In the Entra ID dashboard, select “App registrations” from the left-hand menu.
Step 3: Click on “New registration” and provide the following details:
Name: Enter a name for your application.
Supported account types: Choose the appropriate option based on your requirements (e.g., “Accounts in this organizational directory only” for single tenant applications). I’m choosing Multitenant for this demonstration.
Redirect URI: First, you should select the platform type to enter the redirect URI. I’m selecting Single-page-application (SPA) because React.JS is a Single-page-application framework. Then specify the URI where Azure AD should redirect users after authentication (e.g., http://localhost:3000 for local development).
Step 4: Click on “Register” to create your application.
Step 4: Configure Authentication Settings
Step 1: After registering your application, navigate to the “Authentication” tab.
Step 2: Under “Redirect URIs,” ensure that the appropriate URIs are listed for redirecting users after authentication.
Step 3: Configure any additional authentication settings as needed, such as enabling ID tokens or access tokens.
Step 4: Then navigate to API permissions, select “Add permission”, and select the Microsoft Graph. Then Select the Delegated permissions and search for “User.ReadWrite.All”. Then add the permission and select “Grant admin consent to YOUR_TENENT_NAME”.
Step 5: Note Application Details
Once you’ve registered your application and configured authentication settings, make note of the following details:
Application (client) ID: This is the unique identifier for your application.
Directory (tenant) ID: This is the unique identifier for your Azure AD tenant.
Redirect URI: The URI where Azure AD should redirect users after authentication.
Keep these details handy as we’ll need them when integrating Azure AD authentication into our React.js application using the MSAL library.
Congratulations! You’ve successfully set up Azure Active Directory (Azure AD) and registered your application. In the next steps, we’ll dive into integrating Azure AD authentication into our React.js application using the MSAL library.
Integrating MSAL into React.js
Now that we’ve set up Azure Active Directory (Azure AD) and registered our application, it’s time to integrate the Microsoft Authentication Library (MSAL) into our React.js application. MSAL will enable us to authenticate users against Azure AD and manage their access tokens securely. Let’s get started!
Step 1: Install MSAL Library
Open your terminal and navigate to your React.js project directory. Install the MSAL library using npm or yarn:
npm install @azure/msal-browser
or
yarn add @azure/msal-browser
Step 2: Create MSAL Configuration
Create a file named msalConfig.js in your project’s src directory. This file will contain the configuration settings for MSAL. Here’s an example configuration:
import { PublicClientApplication } from "@azure/msal-browser";
const MSAL_CONFIG = {
auth: {
clientId: "YOUR_CLIENT_ID",
authority: "https://login.microsoftonline.com/YOUR_TENANT_NAME.onmicrosoft.com",
redirectUri: "http://localhost:3000",
},
cache: {
cacheLocation: "localStorage",
storeAuthStateInCookie: false,
},
};
const LOGIN_REQUEST = {
scopes: ["openid", "offline_access"]
};
const TOKEN_REQUEST = {
scopes: ["User.ReadWrite.All"]
};
const GRAPH_CONFIG = {
graphUsersEndpoint: "https://graph.microsoft.com/v1.0/users"
};
const PUBLIC_CLIENT_APPLICATION = new PublicClientApplication(MSAL_CONFIG);
async function initializeMsal() {
await PUBLIC_CLIENT_APPLICATION.initialize();
}
initializeMsal();
export {
MSAL_CONFIG,
LOGIN_REQUEST,
TOKEN_REQUEST,
GRAPH_CONFIG,
PUBLIC_CLIENT_APPLICATION
};
Replace ‘YOUR_CLIENT_ID’ with your Azure AD application’s client ID and ‘YOUR_TENANT_NAME’ with your Azure AD tenant ID.
Step 3: Authenticate Users & Get Access Token
Now, let’s implement user authentication in our React.js application. Create a component or a utility file where you’ll handle authentication logic. Here’s a basic example of sign-in and sign-out functions:
const handleSignIn = async () => {
const loginResponse = await PUBLIC_CLIENT_APPLICATION.loginPopup(LOGIN_REQUEST);
if (loginResponse.account) {
PUBLIC_CLIENT_APPLICATION.setActiveAccount(loginResponse.account);
}
const tokenResponse = await PUBLIC_CLIENT_APPLICATION.acquireTokenSilent(TOKEN_REQUEST);
setToken(tokenResponse.accessToken);
}
const handleSignOut = async () => {
if (!interactionInProgress) {
setInteractionInProgress(true);
PUBLIC_CLIENT_APPLICATION.logout();
setToken(null);
setInteractionInProgress(false);
}
}
And also you can create a function to refresh the Access token. Here’s a basic example of the refresh access token function.
const handleRefreshToken = async () => {
const tokenResponse = await PUBLIC_CLIENT_APPLICATION.acquireTokenSilent(TOKEN_REQUEST);
setToken(tokenResponse.accessToken);
}
You’ve successfully integrated the Microsoft Authentication Library (MSAL) into your React.js application! Users can now sign in using their Azure AD credentials, and your application can securely obtain access tokens for calling protected APIs.
Conclusion
Congratulations on completing the integration of the Microsoft Authentication Library (MSAL) into your React.js application! By leveraging Azure Active Directory (Azure AD) for authentication, you’ve taken a significant step towards enhancing the security of your web application.
Throughout this journey, we’ve covered the following key points:
Setting Up Azure AD: We created an Azure AD tenant, registered our application, and configured authentication settings to enable secure authentication with Azure AD.
Integrating MSAL into React.js: We installed the MSAL library, initialized the MSAL instance, and implemented authentication logic to enable users to sign in and acquire access tokens securely. By following these steps, you’ve empowered your React.js application with robust authentication capabilities, ensuring that only authorized users can access your application’s resources.
Demo Project and Support
To see a complete demonstration of the integration of MSAL into a React.js application, you can check out the Demo Project Repository.
Subscribe to my newsletter
Read articles from Chai-dev682 directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Chai-dev682
Chai-dev682
I like Challenge, Champion, Competition