I came across an interesting scenario recently: I was working with a React SPA which used Azure AD for authenticating users, and it needed to work with multiple accounts logged in simultaneously. Specifically, we were building an Azure AD
multi tenant application which needed to login to multiple M365 and Azure
tenants and allow the user to manage all tenants at the same time.
The good thing was that MSAL v2 does support working with multiple accounts at the same time.
So in this post, let's see how we are able to do that in a React SPA with MSAL js.
Before looking at the code, we would need to create a multi tenant Azure AD
app which would be used to sign in to the different tenants. Step by step
The very first thing we would need is to setup the configuration for our
You will notice the authority is set to the /organizations end point. This is
because our app is a multi-tenant app which would be used to login to
With the config, we will now initiate a PublicClientApplication in the
Now lets get to the most important App.tsx
There are multiple things happening here. Let's unpack them one by one.
First, we are using the MSAL react useMsalAuthentication hook to setup
the authentication and get the login method which we will use later.
What is also important is the prompt: 'select_account' property in
the request which would help us login with a new account when we are already
signed in with one account.
The AuthenticatedTemplate and UnauthenticatedTemplate MSAL react components help us display different views when at least one user is logged in or no user is logged in respectively.
Next, lets look at the ProfileContent.tsx component:
Based on the homeId of passed in to this component as a property, we are using the PublicClientApplication.acquireTokenSilent
method to first get the access token of the relevant user.
Once the accessToken is fetched, we are making a call to the Microsoft Graph to get the basic details of the user. We are using the callMsGraph function for this.
The ProfileData component takes in all properties fetched from the graph and displays it.
The handleLogout function uses the PublicClientApplication.logoutRedirect function to log out the specific user.
So after everything is in place, we would be able to work with multiple users logged in simultaneously at the same time.
Hope this helps!