In today’s digital age, having a robust authentication system is a must for any web application. The Microsoft Identity Platform provides developers with a secure and scalable authentication solution that can be easily integrated into Next.js applications. In this article, we will see how we can integrate Microsoft Login in Next.Js.
Introduction to Microsoft Outlook Login and Next.js
Microsoft provides developers with the Microsoft Identity Platform, which offers a secure and scalable authentication solution for web and mobile applications. Next.js is a popular React framework that allows developers to build server-side rendered web applications easily. By integrating Microsoft login in Next.js, you can provide users with a simple and secure authentication mechanism.
Prerequisites
- Node.js (v12 or later)
- NPM (v6 or later)
- Visual Studio Code (optional)
Setting Up Microsoft Azure
To use the Microsoft Identity Platform, you need to create a new Azure Active Directory (AD) tenant and register your application with Azure AD. Follow these steps to set up Microsoft Azure:
- Go to the Azure Portal and sign in with your Microsoft account.
- Click on Create a Resource and search for Azure Active Directory.
- Click on Create to create a new Azure AD tenant.
- Once the Azure AD tenant is created, go to the App Registrations section and click on New Registration.
- Enter a name for your application and select Web as the application type.
- In the Redirect URI section, enter the URI for your Next.js application (e.g.,
http://localhost:3000/auth/callback
). - Click on Register to register your application with Azure AD.
- Note down the Application (client) ID and Directory (tenant) ID. You will need these values later.
Creating a Next.js Application
Now that we have set up Microsoft Azure, we can create a new Next.js application. Follow these steps to create a new Next.js application:
- Open your terminal and navigate to the directory where you want to create your Next.js application.
- Run the following command to create a new Next.js application:
npx create-next-app my-app - Once the application is created, navigate to the application directory:
cd my-app
Installing Required Packages
To integrate Microsoft login in Next.js, we need to install the following packages:
@azure/msal-react
: This package provides React components and hooks for authentication with the Microsoft Identity Platform.dotenv
: This package allows us to load environment variables from a.env
file.
npm install @azure/msal-react dotenv
Configuring Environment Variables
Next, we need to configure our environment variables. Create a new file called .env.local
in the root of your Next.js application and add the following values:
NEXT_PUBLIC_MSAL_CLIENT_ID=<your_client_id>
NEXT_PUBLIC_MSAL_AUTHORITY=https://login.microsoft
Creating Login and Logout Components
Now we need to create two components: Login
and Logout
. These components will render a button the user can click to either login or log out from the application.
Create a new file called LoginButton.js
in the components
directory and add the following code:
import { useMsal } from "@azure/msal-react";
const LoginButton = () => {
const { instance } = useMsal();
const handleLogin = async () => {
await instance.loginPopup();
};
return <button onClick={handleLogin}>Login</button>;
};
export default LoginButton;
Create another file called LogoutButton.js
in the components
directory and add the following code:
import { useMsal } from "@azure/msal-react";
const LogoutButton = () => {
const { instance } = useMsal();
const handleLogout = async () => {
await instance.logout();
};
return <button onClick={handleLogout}>Logout</button>;
};
export default LogoutButton;
Implementing Login and Logout Logic
import { MsalProvider } from "@azure/msal-react";
import { PublicClientApplication } from "@azure/msal-browser";
import { useEffect, useState } from "react";
const msalInstance = new PublicClientApplication({
auth: {
clientId: process.env.NEXT_PUBLIC_MSAL_CLIENT_ID,
authority: process.env.NEXT_PUBLIC_MSAL_AUTHORITY,
},
cache: {
cacheLocation: "sessionStorage",
storeAuthStateInCookie: true,
},
});
export default function AuthProvider({ children }) {
const [isAuthenticated, setIsAuthenticated] = useState(false);
useEffect(() => {
msalInstance.handleRedirectPromise().then(() => {
setIsAuthenticated(msalInstance.getAccount() !== null);
});
}, []);
return (
<MsalProvider instance={msalInstance}>
{isAuthenticated ? (
<>
{children}
<LogoutButton />
</>
) : (
<LoginButton />
)}
</MsalProvider>
);
}
Securing Pages with Authentication
To secure pages with authentication, we need to wrap them in the withAuth
higher-order component. Create a new file called withAuth.js
in the lib
directory and add the following code:
import { useMsal } from "@azure/msal-react";
import { useRouter } from "next/router";
import { useEffect } from "react";
export default function withAuth(Component) {
return function AuthenticatedComponent(props) {
const { instance } = useMsal();
const router = useRouter();
useEffect(() => {
if (!instance.getAccount()) {
router.push("/");
}
}, []);
return <Component {...props} />;
};
}
Now, let’s secure a page with authentication. Create a new file called profile.js
in the pages
directory and add the following code:
import withAuth from "../lib/withAuth";
const ProfilePage = () => {
return <h1>Profile Page</h1>;
};
export default withAuth(ProfilePage);
Testing the Application
Finally, let’s test the application. Start the development server by running the following command:
npm run dev
Conclusion
In this article, we have learned how to integrate Microsoft Outlook Login in a Next.js application. We have used the Microsoft Authentication Library (MSAL) to handle the authentication process and secure pages with authentication.
Follow Us on
https://www.linkedin.com/company/scribblers-den/
https://www.facebook.com/scribblersden.blogs
Read More
https://scribblersden.com/what-is-technical-debt-understanding-the-costs-and-solutions/
Thank You