Categories

Thursday, September 19, 2024
#919814419350 therichposts@gmail.com
ReactjsReactjs Tutorial

Integrate login validation with Microsoft in a React application

Integrate login validation with Microsoft in a React application

Hello guys, how are you? Welcome back to my blog. Guys today in this blog post, I am going to share Integrate login validation with Microsoft in a React application.
To integrate login validation with Microsoft in a React application, you can use MSAL (Microsoft Authentication Library) for authenticating users through Azure Active Directory (Azure AD). Below is a step-by-step guide to set up Microsoft login validation in your React application:

For react js new comers, please check the below links:

  1. Reactjs Tutorials
  2. Bootstrap 5
  3. React Free Ecommerce Templates
  4. React Free Admins

1. Set up an Azure AD Application Guys

  • Sign in to the Azure Portal.
  • Navigate to Azure Active Directory.
  • In the left-hand menu, click on App registrations > New registration.
  • Register your app by providing the required information:
  • Name: Choose a name for your app.
  • Supported account types: Select the type of users who can use your app.
  • Redirect URI: Add the redirect URI, e.g., http://localhost:3000, if you’re testing locally.
  • Once registered, copy the Application (client) ID and Directory (tenant) ID from the app’s overview page.

2. Install MSAL for React Guys

Guys In your React app, install the MSAL package:

npm install @azure/msal-browser @azure/msal-react

3. Configure MSAL in your React App Guys

Guys Create an MSAL configuration file (e.g., msalConfig.js) with your Azure AD details:

import { PublicClientApplication } from "@azure/msal-browser";

const msalConfig = {
    auth: {
        clientId: "YOUR_CLIENT_ID", // Application (client) ID from Azure portal
        authority: "https://login.microsoftonline.com/YOUR_TENANT_ID", // Directory (tenant) ID
        redirectUri: "http://localhost:3000", // Your redirect URI
    },
    cache: {
        cacheLocation: "localStorage", // This configures where your cache will be stored
        storeAuthStateInCookie: false, // Set to true if you experience issues on IE11 or Edge
    },
};

export const msalInstance = new PublicClientApplication(msalConfig);

4. Guys Implement MSAL Provider in React

Guys now Wrap your app with the MsalProvider to enable MSAL throughout the app. Update your index.js or App.js file:

import React from "react";
import ReactDOM from "react-dom";
import { MsalProvider } from "@azure/msal-react";
import { msalInstance } from "./msalConfig";
import App from "./App";

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

5. Guys Now Add Microsoft Login Button and Handle Authentication

Guys now Inside a component (e.g., Login.js), add a login button using the MSAL hooks:

import React from "react";
import { useMsal } from "@azure/msal-react";

const Login = () => {
    const { instance } = useMsal();

    const handleLogin = () => {
        instance.loginPopup({
            scopes: ["user.read"] // Define scopes based on your requirements
        })
        .then(response => {
            console.log("User logged in:", response);
        })
        .catch(error => {
            console.error("Login failed:", error);
        });
    };

    return (
        <div>
            <button onClick={handleLogin}>Login with Microsoft</button>
        </div>
    );
};

export default Login;

6. Guys Now Retrieve User Information

Guys Once logged in, you can access the authenticated user’s information (e.g., display name, email, etc.) like this:

import React from "react";
import { useMsal, useAccount } from "@azure/msal-react";

const UserInfo = () => {
    const { accounts } = useMsal();
    const account = useAccount(accounts[0] || {});

    if (account) {
        return (
            <div>
                <p>Welcome, {account.name}!</p>
                <p>Email: {account.username}</p>
            </div>
        );
    }

    return null;
};

export default UserInfo;

7. Guys Protecting Routes (Optional)

Guys To protect specific routes and allow only authenticated users, you can implement a check using MSAL. Example:

import React from "react";
import { useIsAuthenticated } from "@azure/msal-react";
import { Redirect } from "react-router-dom";

const ProtectedRoute = ({ children }) => {
    const isAuthenticated = useIsAuthenticated();

    return isAuthenticated ? children : <Redirect to="/login" />;
};

export default ProtectedRoute;

8. Logout

You can also implement a logout button to end the session:

import React from "react";
import { useMsal } from "@azure/msal-react";

const Logout = () => {
    const { instance } = useMsal();

    const handleLogout = () => {
        instance.logoutPopup().catch(error => {
            console.error("Logout failed:", error);
        });
    };

    return <button onClick={handleLogout}>Logout</button>;
};

export default Logout;

That’s it!

You now have Microsoft login validation integrated into your React app! You can further customize the authentication flow by exploring other methods like loginRedirect and managing tokens based on your requirements.

This is it guys and if you will have any kind of query, suggestion or requirement then feel free to comment below.

Thanks

Ajay

therichpost
the authortherichpost
Hello to all. Welcome to therichpost.com. Myself Ajay Malhotra and I am freelance full stack developer. I love coding. I know WordPress, Core php, Angularjs, Angular 14, Angular 15, Angular 16, Angular 17, Bootstrap 5, Nodejs, Laravel, Codeigniter, Shopify, Squarespace, jQuery, Google Map Api, Vuejs, Reactjs, Big commerce etc.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.