1

We are using MSAL 2.0 in our REACT SPA for authentication. The root App component implements a react higher order component (HOC) that handles the authentication part. In the authentication logic how do we check if a user is logged in after initial sign in to avoid re-rendering the logic related to acquiring user information from graph api. The requirement is after the user login for the first time and retrieve the info from graph api, the application should reuse the info until the login is expired. What is the best approach here?

  • 1
    If my answer is helpful for you, you can accept it as answer( click on the check mark beside the answer to toggle it from greyed out to filled in.). See https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work This can be beneficial to other community members. Thank you. – Carl Zhao Jan 11 '21 at 02:13

2 Answers2

0

The easiest way is to parse the id token or access token, and then view the oid claim, it is your user id, it will appear in your token when you log in to the user. You can find it by parsing the token, and then determine whether the user is logged in.

enter image description here

Carl Zhao
  • 8,543
  • 2
  • 11
  • 19
0

This is a great question and a little concerning that it is not brought up more. I have been instructed throughout my career to logout of application that I am not using to reduce my attack surface, but MSAL seems to be trying to make this harder. For instance, the default Single Sign On using cookies. It seems like a man in the middle that caches every apps tokens, allows signing into new apps without notifying the user, and suggests keeping tokens active longer than needed.

It seems like it should be best practice to always check if the user is already authenticated and provide a logout button. This would both notify the user that they have an active token as well as allow them to logout.

I have seen another suggestion for "handling not knowing if the user is signed in" on stack overflow (can't find the link) that suggests just ensuring the token by calling acquireTokenSilent. Ultimately this is just promoting keeping tokens alive forever without the user’s knowledge.

Carl Zhao's suggestion of parsing the token yourself is a workaround but your response is a valid concern since we are working with a library that is supposed to abstract this need for knowledge away; suggesting an underlying issue with the library. Microsoft's You Tube video (around 7:01) instructs us not to do parse the token ourselves . It's a bit convoluted because Microsoft talks about reading from the Id token but not the Access Token; however both are required to have access to the API; there for both would have to be valid to be “LoggedIn”

My suggestion: make a request to an endpoint that requires authorization and handle the 401 (unauthorized) status code. :(

kevin
  • 338
  • 2
  • 13