Msal-React: Fetching Job Info from Microsoft Graph

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

If you ever wondered how to get job information from Microsoft Graph, even after reading all the answers on StackOverflow, you’ve come to the right place!

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 AD configuration

To start off with we are going to need to configure our Azure AD.
First, let's take a look at the App Registration:

In the API Permissions tab, we need to grab a couple of scopes

Azure Portal -> App Registrations -> API Permissions

After we have given ourselves these, we also need to expose our API to the User.Read scope. Which we can do from the Expose an API tab.

Switch <application-id> for you own id.

Make sure you add your client and assign the scope. Once this is done we can move over to our code.

Code Implementation

The following code is structured as a React component and currently does not interact with the child components. If you want to pass the job information to the child components you can easily edit the code.

There are two main steps, first, we want to get an access token with the appropriate scope, and then call MS Graph and query for our data.

We have a config file (imported at line 3 and used on line 25) that contains our tenant Id, you will need this to get an access token.

I store the job info (department) in localStorage in this example so that it can be reused. You could also use Redux or any other storage library.

Queries

When fetching data from graph we can choose what we want to get out, such as JobTitle and displayName . More examples can be found here, there is also a graph explorer to test queries here.

--

--