I have recently got an opportunity to deal with the authentication of a React App with azure B2C.
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).
- Setup the initial react app project locally. (create-react-app)
- 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
step 3: initialize the MSAL
In the constructor, you can initialize the MSAL instance with azure b2c.
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.
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.