15

With msal.js library (The Microsoft Authentication Library), which is the way to know if a given user is already logged in? My intention is to avoid to show login pop-up if the user's credentials are already saved in browser's storage

My current approach:

function isUserLoggedIn(username) {
 const agent = msal.UserAgentApplication(...);
 const user = agent.getUser();
 return user != null && user.displayableId === username);
}

But I'm not sure if I have to check if the user credentials are outdated/expired. Which is the proper way to go?

Daniel San
  • 1,937
  • 3
  • 19
  • 36

2 Answers2

15

With the MSAL agent instance, you can get user information because it is cached. Getting information (such as the userId) doesn't mean that the user's credentials are still valid (logged in). To be 100% sure that the user is logged in, ask for a token

const promise = agent.acquireTokenSilent(...)

If the user is not logged in, the promise will be rejected with the error code user_login_error If, on the other hand, the user is still logged in, the promise will be resolved

Daniel San
  • 1,937
  • 3
  • 19
  • 36
  • `agent.acquireTokenSilent(...)` will also be resolved if user is cached , for example I log in to my website using msal, and then I log out of the office account on the office.com. If I create middleware to use your `acquireTokenSilent(...)` it will give me the user logged in from the cache instead saying it is logged out. Do you know how to fix this ? – Jozef Barca Oct 05 '21 at 08:22
  • 1
    @JozefBarca if I remember correctly, there should be a configurable "single-sign-out" url for your application in ActiveDirectory. when the user logs out from application A, application A should redirect the user to the tenant's "log out url". This deactivates the session in the tenant. the ActiveDirectory tenant should then notify the other applications that the user has signed out by invoking their "single-sign-out" url webhooks. This allows all the other related apps to log the user out locally. I think the feature is (or was) referred to as Single-Log-Out. – bpossolo Jan 29 '22 at 01:04
  • predicating a decision on an error is not the best practice.. @Hussein Dahir answer should be marked as the accepted answer – I Stand With Russia Mar 29 '22 at 19:34
10

From MSAL samples, they were checking this way:

let isLoggedIn = this.authService.instance.getAllAccounts().length > 0;
Hussein Dahir
  • 395
  • 4
  • 14