Office 365 login in Next.js using NextAuth.js

Secure user authentication using O365 (Azure Active Directory)

Avani Bataviya
Simform Engineering

--

In today's digital world, we spend our days engaging in various online activities. With the rise of online interaction, it becomes necessary for engineers to authenticate users and give access to a system or service to validate users only.

The most often used method of authentication is now using Google, Microsoft Office, and other services since it becomes more difficult for us to remember usernames and passwords as we connect with several platforms.

If you've ever found yourself writing too many lines of code across multiple files to implement user authentication for any provider, then NextAuth.js is the perfect solution.

Why NextAuth.js?

NextAuth.js is the most popular open-source complete authentication solution for the Next.js app. It's an easy, secure, and flexible solution because of the following:

  • Built-in support for many providers, i.e., Facebook, Apple, Auth0, Google, Amazon Cognito, Discord, GitHub, GitLab, Instagram, LinkedIn, and many more, or you can provide your custom provider.
  • It supports many signing options, i.e., username-password, email, passwordless, and magic link.
  • Work with any database and are built to support serverless environments.
  • Secure options HTTP POST + CSRF Token, JWT Token, and use session-only cookies.

Create a Next.js app

Use the create-next-app command and provide the required information to create the Next.js app.

To integrate O365 login, you must first register your app on the Azure Portal (https://portal.azure.com/) to give users access to a specific active directory.

Register the app on the Azure portal

Follow the below steps to register for the new app:

  1. Go to https://portal.azure.com/
  2. Search for Azure Active Directory in your organization and select App Registrations from the left panel and click on New registration .
app registration on the Azure portal

3. Register the application by giving your name, selecting supported account types (who can use this application) based on requirements, and clicking register.

azure application registration steps

4. Click on Client credentials and create a new client secret.

5. Register redirect URL, https://yourapplication.com/api/auth/callback/azure-ad or for development http://localhost:3000/api/auth/callback/azure-ad.

configure redirect URL in the Azure application

6. Copy the app's essential info, create .env.local a file at the root of your project and set the value of the below .env variables.

azure app info
NEXT_PUBLIC_AZURE_AD_CLIENT_ID= 
NEXT_PUBLIC_AZURE_AD_CLIENT_SECRET=
NEXT_PUBLIC_AZURE_AD_TENANT_ID=
NEXTAUTH_SECRET=
NEXTAUTH_URL=

Here, NEXT_PUBLIC_AZURE_AD_CLIENT_ID means Application (client) ID, NEXT_PUBLIC_AZURE_AD_CLIENT_SECRET means Client secret (value), NEXT_PUBLIC_AZURE_AD_TENANT_ID means Directory (tenant) ID, NEXTAUTH_SECRET will be a random string that is used to encrypt the NextAuth.js JWT token andNEXTAUTH_URL will be your project URL for development purposes; it should be http://localhost:3000.

Configure NextAuth.js

Install the next auth by running npm install next-auth command and create […nextauth].js file in the folder pages/api/auth.

From NextAuth.js, you will use AzureAD Provider to implement O365 login. So let's configure it by providing clientId, clientSecret, tenantId, and authorization in […nextauth].js file.

Callbacks are asynchronous functions used to control data when some action is performed. When using JSON Web Tokens, you can store the data in the token when the jwt callback is called, then transfer the data to the browser in the session callback, and those data will be available in the application using useSession() NextAuth.js hook. (We will use this hook ahead.)

Setup a login button

Add a login button in index.js file.

On button click, we are calling signIn() method of NextAuth.js with provider name azure-ad, callbackUrl mean on which user will redirect after login and theprompt the method will be used for login.

Configure SessionProvider

To use session data anywhere in the application (by using useSession() hook) need to provide SessionProvide at the top level of the application, which means in _app.js file. It will work like the React Context API under the hood.

Create a dashboard page.

On successful login, the user be redirected to the dashboard page, and here they will see their username, email, token, and logout button.

dashboard

Use the useSession() NextAuth.js hook to check whether the user is signed in or not anywhere in the app. It returns data and status. The possible statuses can be “loading” | “authenticated” | “unauthenticated" and on successful logging, the data will contain the session value you specified in the […nextauth.js] app callback.

Refresh token

From the above code, you will be able to log in, but Azure Active Directory will provide a token lifetime of between 60 to 90 minutes, so after that, you need to refresh the token.

As shown below, you need to check if the token is expired or not using Date.now() < token.accessTokenExpires — 100000 || 0 in the jwt callback, and if the current time is less than the token expiration time, send the token or refresh the token.

Create a refresh token request using the above code, making sure to include the necessary information and grant_type: ‘refresh_token’ in the request.

Output

Office 365 login in Next.js using NextAuth.js

You can find the above source code on the GitHub Repository 🚀

Conclusion

We have explored the steps to register the app in the Azure portal and seen how easy it is to use any provider with NextAuth.js to implement user authentication.

With the example provided, it's clear that NextAuth.js offers a powerful way for building authentication that supports JSON Web Tokens and database sessions.

Stay tuned and follow Simform Engineering for important and exciting updates on various tools and technologies.

--

--