<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Janitha Amarasiri Jayasinghe on Medium]]></title>
        <description><![CDATA[Stories by Janitha Amarasiri Jayasinghe on Medium]]></description>
        <link>https://medium.com/@janithaaj?source=rss-3d86962e4b9a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Abj4TtQRzZNs4YjSR5vDYA.jpeg</url>
            <title>Stories by Janitha Amarasiri Jayasinghe on Medium</title>
            <link>https://medium.com/@janithaaj?source=rss-3d86962e4b9a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 04:46:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@janithaaj/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Fortify Your React.js Apps with Azure AD Authentication & MSAL]]></title>
            <link>https://medium.com/@janithaaj/build-secure-react-js-apps-azure-ad-authentication-with-msal-5363f222d8c6?source=rss-3d86962e4b9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/5363f222d8c6</guid>
            <category><![CDATA[login]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react-js-tutorials]]></category>
            <category><![CDATA[azure-ad-authentication]]></category>
            <category><![CDATA[microsoft]]></category>
            <dc:creator><![CDATA[Janitha Amarasiri Jayasinghe]]></dc:creator>
            <pubDate>Sat, 21 Oct 2023 06:19:07 GMT</pubDate>
            <atom:updated>2023-10-23T03:43:47.132Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*ojk0tfYs6T9igOuYD6RPsg.png" /><figcaption>AD Authentication &amp; MSAL</figcaption></figure><h3>FortifyYour React.js Apps with Azure AD Authentication &amp; MSAL</h3><h3><strong>Introduction</strong></h3><p>In today’s digital world, ensuring the security of your web applications is paramount. One fundamental aspect of this security is user authentication and authorization. Azure Active Directory (Azure AD) is a robust solution for achieving this, and Microsoft Authentication Library (MSAL) makes it easier than ever to integrate Azure AD into your React.js applications. In this article, I will guide you through the steps to integrate Azure AD authentication using the @azure/msal-browser and @azure/msal-react libraries in your React.js app. This process will not only enhance the security of your application but also make it more user-friendly and accessible.</p><h3><strong>Prerequisites</strong></h3><p>Before get started on the integration process, see to it that the following prerequisites are in place:</p><ol><li>A React.js application: If you don’t already have one, create a basic React.js application using Create React App: <a href="https://create-react-app.dev/">https://create-react-app.dev/</a></li><li>You need an Azure AD tenant to configure your application. If you don’t have one, you can create it through the Azure Portal</li><li>Azure AD App Registration: Create an Azure AD App Registration to represent your React.js app in Azure AD. This registration will provide you with the necessary client ID and other configuration settings.</li></ol><p><strong>Integration</strong></p><p><strong>Step 1: Azure AD App Registration</strong></p><ol><li>Go to the Azure Portal and navigate to the Azure Active Directory service.</li><li>Under “App registrations,” create a new app registration for your React.js application.</li><li>Save the Application (client) ID, you will need this in the React.js app.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*Asd0Yv93G3xe1GANIMI1Mw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*_1fNgSA97004--5EQ5zJ2g.png" /></figure><p>4. Add any necessary API permissions or scopes your app will need.</p><p>5. Save your configuration.</p><p><strong>Step 2: Set Up Your React.js Application</strong></p><ol><li>create a basic React.js application using Create React App.</li></ol><pre>npx create-react-app ad-login-app<br>cd ad-login-app</pre><p>2. Install the @azure/msal-browser and @azure/msal-react libraries using npm or yarn:</p><pre>npm install @azure/msal-browser @azure/msal-react</pre><p>3. Create a configuration file (e.g., authConfig.js) to store your Azure AD settings and export them as constants:</p><pre>import { LogLevel } from &quot;@azure/msal-browser&quot;;<br><br>/**<br> * Configuration object to be passed to MSAL instance on creation.<br> */<br>export const msalConfig = {<br>    auth: {<br>        clientId: &quot;YOUR_CLIENT_ID&quot;,<br>        authority:&quot;https://login.microsoftonline.com/YOUR_TENANT_ID&quot;,<br>        redirectUri: `YOUR_REDIRECT_URL`, //eg: ${window.location.origin}/Dashboard<br>        postLogoutRedirectUri: &quot;/&quot;,<br>        navigateToLoginRequestUrl: false,<br>    },<br>    cache: {<br>        cacheLocation: &quot;&quot;, // &quot;sessionStorage&quot; or&quot;localStorage&quot;<br>        storeAuthStateInCookie: false,<br>    },<br>    system: {<br>        loggerOptions: {<br>            loggerCallback: (level, message, containsPii) =&gt; {<br>                if (containsPii) {<br>                    return;<br>                }<br>                switch (level) {<br>                    case LogLevel.Error:<br>                        console.error(message);<br>                        return;<br>                    case LogLevel.Info:<br>                        console.info(message);<br>                        return;<br>                    case LogLevel.Verbose:<br>                        console.debug(message);<br>                        return;<br>                    case LogLevel.Warning:<br>                        console.warn(message);<br>                        return;<br>                    default:<br>                        return;<br>                }<br>            },<br>        },<br>        allowNativeBroker: false,<br>    },<br>};<br><br>/**<br> * Scopes you add here will be prompted for user consent during sign-in.<br> * By default, MSAL.js will add OIDC scopes (openid, profile, email) to any login request.<br> */<br>export const loginRequest = {<br>    scopes: [&quot;Files.Read&quot;],<br>};<br><br>/**<br> * An optional silentRequest object can be used to achieve silent SSO<br> * between applications by providing a &quot;login_hint&quot; property.<br> */<br>export const silentRequest = {<br>    scopes: [&quot;openid&quot;, &quot;profile&quot;],<br>    loginHint: &quot;example@domain.net&quot;,<br>};</pre><p><strong>Note</strong>: there are two cache options on the config file (cacheLocation):</p><p>localStorage:</p><ul><li>You might use localStorage to store tokens or user state if you want these values to be accessible across different tabs within the same browser session.</li><li>This could be useful if you have a use case where, for instance, you want to share some user-specific data or session information across multiple tabs.</li></ul><p>sessionStorage:</p><ul><li>Using sessionStorage can be appropriate if you want to keep tokens or user state isolated to a specific tab or window.</li><li>sessionStorage is helpful when you want to ensure that authentication tokens are specific to a particular tab or session and aren&#39;t shared across tabs.</li></ul><p>Ultimately, the choice of whether to use localStorage or sessionStorage in the context of Azure AD integration with MSAL depends on your specific requirements for token and user state management and the behavior you want in multi-tab scenarios.</p><p>4. Initialize the msalInstance in the index.tsx or app.tsx file as shown below:</p><pre>import { useEffect } from &quot;react&quot;;<br>import { createRoot } from &quot;react-dom/client&quot;;<br>import App from &quot;./App&quot;;<br>import reportWebVitals from &quot;./reportWebVitals&quot;;<br>import { BrowserRouter, useNavigate } from &quot;react-router-dom&quot;;<br>import {<br>    PublicClientApplication,<br>    EventType,<br>    EventMessage,<br>    AuthenticationResult,<br>} from &quot;@azure/msal-browser&quot;;<br>import { msalConfig } from &quot;./config/authConfig&quot;;<br>import { MsalProvider } from &quot;@azure/msal-react&quot;;<br><br>const msalInstance = new PublicClientApplication(msalConfig);<br><br>//get initialize msalInstance<br>msalInstance.initialize();<br><br>const activeAccount = msalInstance.getActiveAccount();<br><br>if (!activeAccount) {<br>    // Account selection<br>    const accounts = msalInstance.getAllAccounts();<br>    if (accounts.length &gt; 0) {<br>        msalInstance.setActiveAccount(accounts[0]);<br>    }<br>}<br><br>//set the account<br>msalInstance.addEventCallback((event: EventMessage) =&gt; {<br>    if (event.eventType === EventType.LOGIN_SUCCESS &amp;&amp; event.payload) {<br>        const authenticationResult = event.payload as AuthenticationResult;<br>        const account = authenticationResult.account;<br>        msalInstance.setActiveAccount(account);<br>    }<br>});<br><br>//enable account storage event<br>msalInstance.enableAccountStorageEvents();<br><br><br>//App main component<br>function AppComponent() {<br>    const navigate = useNavigate();<br><br>    useEffect(() =&gt; {<br>        msalInstance.handleRedirectPromise().then((response) =&gt; {<br>            if (response &amp;&amp; response.account) {<br>                // User is authenticated, you can proceed to  app<br>                navigate(&quot;/Dashboard&quot;, { replace: true });<br>            }<br>        });<br>        // Check if the user is already signed in<br>        const account = msalInstance.getActiveAccount();<br>        if (account) {<br>            // User is already signed in, you can proceed to  app<br>            navigate(&quot;/Dashboard&quot;, { replace: true });<br>        } else {<br>            // If the user is not signed in, initiate the login process<br>            msalInstance.initialize();<br>        }<br>    }, []);<br><br>    return &lt;App /&gt;;<br>}<br><br>const container = document.getElementById(&quot;root&quot;);<br>const root = createRoot(container!);<br><br>root.render(<br>    &lt;BrowserRouter&gt;<br>        &lt;MsalProvider instance={msalInstance}&gt;<br>            &lt;AppComponent /&gt;<br>        &lt;/MsalProvider&gt;<br>    &lt;/BrowserRouter&gt;,<br>);<br><br>reportWebVitals();</pre><p>5. Wrap the HTML from MsalAuthenticationTemplate with the following structure:</p><pre>import {<br>    useMsal,<br>    MsalAuthenticationTemplate,<br>    useIsAuthenticated,<br>} from &quot;@azure/msal-react&quot;;<br>import {<br>    InteractionType,<br>    InteractionStatus,<br>    IPublicClientApplication,<br>    AccountInfo,<br>} from &quot;@azure/msal-browser&quot;;<br>import Loading from &quot;../components/loading/index&quot;;<br><br><br>const Dashboard: FunctionComponent = () =&gt; {<br>    const { inProgress, instance, accounts } = useMsal();<br>    const isAuthenticated = useIsAuthenticated();<br><br>    if (!isAuthenticated &amp;&amp; inProgress !== InteractionStatus.None) {<br>        return &lt;Loading /&gt;;<br>    }<br>    return (<br>        &lt;MsalAuthenticationTemplate interactionType={InteractionType.Redirect}&gt;<br>                Authenticated component here <br>        &lt;/MsalAuthenticationTemplate&gt;<br>    );<br>};<br><br>export default Dashboard;</pre><p>6. Sign Out functionality implementation as follows</p><pre>// Function to find the AccountInfo based on homeAccountId<br>    const findAccountByHomeAccountId = (<br>        homeAccountId: string,<br>    ): AccountInfo | undefined =&gt; {<br>        return accounts.find(<br>            (account) =&gt; account.homeAccountId === homeAccountId,<br>        );<br>    };<br><br>    const logOut = () =&gt; {<br>        const homeAccountId = accounts[0].homeAccountId;<br>        const accountToSignOut = findAccountByHomeAccountId(homeAccountId);<br>        if (accountToSignOut) {<br>            signOutClickHandler(instance, accountToSignOut);<br>        } else {<br>            console.error(&quot;Account not found for the given homeAccountId&quot;);<br>        }<br>    };</pre><p><strong>Conclusion</strong></p><p>In this article, we explored the process of building secure React.js applications by integrating Azure Active Directory (Azure AD) authentication using the Microsoft Authentication Library (MSAL). We’ve covered the key aspects and best practices to ensure the security of your application.</p><p>If you found this article helpful, I’d greatly appreciate your support. You can do so by following me on Medium, reacting to this post, leaving a comment, or even showing your appreciation by buying me a coffee through this <a href="https://www.buymeacoffee.com/janithaajj">link</a>. <strong>Thank you</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5363f222d8c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>