React App authentication With MSAL.js

Praval Jain
Sep 22, 2019 · 3 min read

I have recently got an opportunity to deal with the authentication of a React App with azure B2C.

Photo by Chris Ried on Unsplash

What is MSAL?

MSAL is a developer library that helps you to obtain tokens from MSA, Azure AD or Azure B2C for accessing protected resources — such as your own API, Microsoft’s API (such as the Microsoft Graph).

  1. Setup the initial react app project locally. (create-react-app)
  2. Setup the Microsoft Azure B2C tenant.

Let’s start the link between MSAL and AAD (Azure Active Directory) so that user can secure signIn in our app.

For installing use npm install msal. Here I am using msal version ^0.2.3

I am using context API for creating the auth context so that I can consume auth context anywhere in my app. Create a file let say authContext.js

creating the AuthContext at the global level of authContext.js

step 3: initialize the MSAL

In the constructor, you can initialize the MSAL instance with azure b2c.

creating the MSAL instance with b2c configuration

So here B2CAPPID, B2CTENANT, REDIRECT_POLICY are app-id, tenant-id and redirect policy respectively that you can get from your Azure tenant (where you registered your app). Redirect policy you can set either it is signup policy or sigin policy.

this.onTokenCallback is the callback function. It gets called when the token is acquired or throw an error.

this is the service functions that I declare in the constructor

You can call acquireTokenSilent method to get the accessToken. In this function, you can write code to embedded the access token with your request.

here GRAPH_SCOPES is equal to [‘openid’]

here you can read more about OpenID https://openid.net/connect/

In step two we create a context for the AuthContext so here in the render method, you can provide the context to the children so they can consume the auth context.

So this way you can authenticate your react app with Azure AD. Feel free to reach out to me if you have any query. You can drop me a mail.

Praval Jain

Software Engineer

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store