Msal-React: Authorize AD Users with Groups

Jakob Madsen
Sopra Steria Norge
Published in
2 min readJan 27, 2022

If you want to limit which AD users can access your application an easy way is to create a custom group!

This guide assumes you have some knowledge using Msal and React, if you are not familiar with these we recommend: Msal-React: Automatically sign in users and get App Roles.

In this guide, we are using the following packages.

  • msal-browser ^2.16.1
  • msal-react ^1.0.1
  • react ^17.0.2
  • react-scripts ^4.0.3

Azure Group

Azure groups can easily be made by going to Groups in the Azure Portal and pressing “New group” as seen in the picture below.

After creating a group you can add members in the Members tab. You should also make note of the Object Id, you will need this later.

While we are in the Azure Group we should also add our Application Registration to the Group. Head over to Applications and find your app.

Code Implementation

In our code, we can check the group claim with Msal. In the following code, we are using the loginRequest from Microsofts guide with our own scopes. After calling acquireTokenSilent our groups can be found as a list in the idTokenClaims property. If you are unsure about the token, you can inspect it using jwt.io.

In this code, we verify our group against validAzureAdGroupId which is passed in as a prop to our component from the parent App.jsx . You can replace <>Unauthorized</> with any other error message or component.

We are using the msalConfig from the Microsoft guide. The example assumes there is only one group, however, this can easily be changed to work with multiple groups.

--

--