Praval Jain
Published in

Praval Jain

React App authentication With MSAL.js

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).

Pre-Required things

  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.

step 1: Install the MSAL library

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

step 2: Set up the authentication into your app

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

step 4: you can get bearer token and embedded in the request

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

step 5: Login, Logout function

here GRAPH_SCOPES is equal to [‘openid’]

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

step 6: Last the render method

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.

--

--

--

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
Praval Jain

Praval Jain

Front-End Engineer based in Bengaluru, India.

More from Medium

Implementing WebSockets plugin for NativeScript using React Native

NestJS + Auth0

NestJS and Auth0

Express and React with concurrently

Setting up a Gatsby App with GraphCMS by building a Photo Gallery App