Code Monkey home page Code Monkey logo

msalwithnextjs14's Introduction

Next.js App Router version >=13 with MSAL (Microsoft authentication library) Integration

This project integrates Next.js v14.0.4 with React v18 and the latest version of MSAL (Microsoft Authentication Library). It's bootstrapped with create-next-app and includes configurations for @azure/msal-browser: v3.6.0 and msal-react: v2.0.8.

This boilerplate is designed to streamline the integration of Azure AD authentication in a server-rendered Next.js application, while ensuring the main layout remains succinct and organized.

image image

Prerequisites

Before you begin, ensure you have Node.js installed, preferable version >=18.x.x

Setting Up Your MSAL Backend and Configurations

To use Azure AD authentication, you must first set up your backend in Microsoft Azure. And also to test the user claims and roles, you need to create a .env.local file in your nextjs project root directory and write the following line in it:

process.env.NEXT_PUBLIC_USER_CLAIMS_ADMIN = '%replaceWithYourAdminRoleNameSpecifiedInAzureRegisteredAppRoles%'
//ex: process.env.NEXT_PUBLIC_USER_CLAIMS_ADMIN = 'APP_ADMIN'

Steps to Configure Azure:

  1. Navigate to Microsoft Azure App Registration.
  2. Create a new registration for your web app.
  3. Note down the following values:
    • Application (client) ID
    • Directory (tenant) ID
    • Managed application name in local directory
    • Your domain name (e.g., xxxxx.onmicrosoft.com)
  4. Update these values in the MSAL authentication configuration file msal/authConfig.js.

Running the App

Use the following commands to run the app:

# Restoring dependencies
npm install

# Build the application
npm run build

# Start the development server
npm run dev

# Browse the application, 3000 is the default Next.js port if not used by another app.
http://localhost:3000/

v0.2.0 Change log:

  • Added User avatar component to handle user photo, or display initials avatar when no photo provided or the photo is blank/corrupted, and whether or not to show the basic user info like name, username.
  • Added user claims handling, and a dedicated component components/UserRolesContainer.tsx to render content based on user claims.
  • Added a page to test Admin only user access.
  • Added a page to test getting the user token generated based on your MSAL configuration, this can be very handy when talking to your custom APIs.
  • All the above are tested and functioning correctly as expected.
  • Added msal/userHelper.ts to help with common user tasks.

Final words

I had the same struggle as you do do when I first started using MSAL for custom Azure hosted API, I hope this helps you starting your MSAL authentication faster, cleaner, and more straight forward.

Happy coding!๐Ÿ’ป

Mazen Alsenih

msalwithnextjs14's People

Contributors

mazensenih avatar

Stargazers

Johnnie Lucas avatar  avatar Gloria avatar Ward Werbrouck avatar Lukas Chiu avatar Kyle Surowiec avatar Karthik Rao avatar Ian avatar  avatar Bruno Prestes avatar  avatar A. Gazi Yavuz avatar Matheus Figueiredo avatar Michael Craddock avatar  avatar Alexei avatar lmik avatar Sivaram Pandariganthan avatar Cyrus avatar Ala Eddine Menai avatar Vukasin Gligorijevic avatar  avatar Ehsan Shahvirdi avatar Lad Jay Sanjay avatar

Watchers

 avatar

msalwithnextjs14's Issues

You must call and await the initialize function before attempting to call any other MSAL API

When I make a change to the code and HMR triggers an update I get this error in console log:

Error acquiring token: BrowserAuthError: uninitialized_public_client_application: You must call and await the initialize function before attempting to call any other MSAL API.  For more visit: aka.ms/msaljs/browser-errors
    at createBrowserAuthError (BrowserAuthError.mjs:274:12)
    at blockAPICallsBeforeInitialize (BrowserUtils.mjs:140:98)
    at preflightCheck (BrowserUtils.mjs:155:5)
    at preflightCheck (StandardController.mjs:80:80)
    at StandardController.acquireTokenPopup (StandardController.mjs:405:13)
    at PublicClientApplication.acquireTokenPopup (PublicClientApplication.mjs:76:32)
    at acquireAccessToken (tokenFetcher.ts:36:47)
    at async getCurrentToken (tokenFetcher.ts:48:13)
    at async getToken (msal.ts:29:21)
    at async fetchToken (page.tsx:11:7)

It looks like at this point the client is not initialised anymore and what I have to do to make my changes work is to always refresh the page after making any change.

Any ideas regarding this?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.