Allowing users to log in using their Microsoft Entra credentials.
Why Auth.js?It is a complete authentication solution. It,
Read more on here
Create Next.js projectCreate a Next.js project by using create-next-app CLI utility that is provided and recommended by Next.js (lets assume your appname is 'tutorial')
npx create-next-app tutorialChoose the prompts, ensure you have App Router selected as yes. I choose default options.
✔ Would you like to use TypeScript? … No / Yes ==> Yes ✔ Would you like to use ESLint? … No / Yes ==> Yes ✔ Would you like to use Tailwind CSS? … No / Yes ==> No ✔ Would you like your code inside a `src/` directory? … No / Yes ==> No ✔ Would you like to use App Router? (recommended) … No / Yes ==> Yes ✔ Would you like to use Turbopack for `next dev`? … No / Yes ==> Yes ✔ Would you like to customize the import alias (`@/*` by default)? … No / Yes ==> NoAuth.js encrypts (JWT) tokens, for that it uses cryptographically secure random string which is of at-least 32 characters. It expects that random string to be identified by 'AUTH_SECRET' environment variable. Auth.js provides CLI command to generate it which also adds it to environment file. It does so by,
npx auth secretThis creates secure random string, assigns it to environment variable AUTH_SECRET and adds it to .env.local file. The file will be placed in the directory where the command is executed, so ensure that you execute it in the root folder of your application.
To the .env.local file add other environment variables that are needed.
AUTH_MICROSOFT_ENTRA_ID_ID="You will get the values from Azure portal.
Complete .env.local file should look like
AUTH_SECRET="auth.ts file is the core of the authentication setup. It defines how Auth.js integrates with providers such as Microsoft Entra ID. It manages authentication, session and token handling.
Steps to ConfigureIn Next.js, authentication requests (e.g., /api/auth/signin, /api/auth/session) need to be handled dynamically. The app/api/auth/[…nextauth]/route.ts file links the routing system to the handlers exported from auth.ts.
Purpose of […nextauth]Test Sign in
Visit
You should see a sign-in page with Microsoft Entra ID listed as a provider. Login using your valid Microsoft Entra ID credentials.
Test logged in user details
Visit
You should see session data, including the user’s email, name, and token expiration time.
Test Sign out
Visit
You should be logged out and the session should be cleared.
\ By following these steps, you’ve successfully configured Microsoft Entra ID as a login provider in your Next.js app using Auth.js!
All Rights Reserved. Copyright , Central Coast Communications, Inc.