While working on a project applying React using create-react-app in the frontend, .Net Core 2.2 in the backend and AzureAD for authentication, I find it extremely hard to search for a ready-made solution how to make it work properly in a React app. I know there are lots of articles about using ADAL but the trend is moving towards MSAL.
For the sake of clarity, this article will focus heavily on implementation of MSAL (Microsoft-Authentication-Library-For-JS) to facilitate authentication of users and get access token from Azure AD.
(Prefer to know what are the differences and why you should choose MSAL over ADAL? Read more here: https://docs.microsoft.com/en-us/azure/active-directory/develop/msal-compare-msal-js-and-adal-js)
1. Installing MSAL using npm
I assume you have already registered your application in Azure AD. In order to use MSAL, you install it first by running this command below:
npm install msal
2. Implementation
Next up, in the src folder, create a file named auth-utils.js. Inside this file, you can create instance of UserAgentApplication and configure it with your clientId from Azure AD and scopes correctly depending on which environment you’re running using if/else statement. You’re free to choose between sessionStorage or localStorage when it comes to caching.
The main idea is to create a HOC (High Order Component) to wrap around your App Component. This AuthProvider HOC contains all of the logic for login, logout and acquire token silently without prompting the user (using hidden frames). In this example, only redirect login is applied but you can modify to switch it to popup login if needed. In componentDidMount life cycle method, call onSignIn() method to redirect user to the login page.
Import AuthProvider and wrap it around your App. So now, App component has access to the props passed down to it by HOC AuthProvider. When users first enter the page, they have to login in order to use your App. Successful login will return accountInfo as a prop to your App. Then you can use it to consider rendering logout button and call onSignOut() function once the user clicks on Signout button.
It’s pretty much a wrap for implementing authentication with Azure AD in the frontend. Next up, I will show you how to call your APIs with Authorization Header using Access Token and to get a new token silently (with no page reload) when it expires. See you soon!
