@azure/msal-node: Is there a way to log out / invalidate tokens?

Viewed 4252

I'm using the @azure/msal-node package in a node application to enable my users to log in using their AzureAD credentials. Logging in and acquiring session tokens works fine, but I cannot find a way to invalidate a session / log out a user - am I overlooking something obvious here?

Just for context, here's how I'm getting my tokens:

// msalConfig is my valid config object
const msalApp = new msal.ConfidentialClientApplication(msalConfig); 

const authCodeUrlParameters = {
  scopes: ['user.read'],
  redirectUri: BASE_URL + '/msal-redirect'
};

try {
  const authCodeResponse = await msalApp.getAuthCodeUrl(authCodeUrlParameters);
  reply.redirect(authCodeResponse);
} catch (e) {
  logError('auth code redirect error', e);
}

In the redirect handler, I'm doing this:

const tokenResponse = await msalApp.acquireTokenByCode({
  code: request.query.code,
  scopes: ['user.read'],
  redirectUri: BASE_URL + '/msal-redirect'
});

and then I'm using that token to display the logged in user etc.

What I'm missing is something like msalApp.logout() - what am I not seeing here?

2 Answers

Unfortunately MSAL does not currently contain an msalApp.logout() API. Instead, you will have to manually implement the steps.

A logout operation will contain multiple steps:

  • Removing the account and the tokens from the msal application cache.
  • Redirecting to the AAD logout endpoint so the user logs out and AAD cookies are deleted.
  • If your webapp has a session, invalidating it.

For removing the account and tokens from the msal application cache, you can do something along the lines of:

const accounts = msalApp.getTokenCache().getAllAccounts();
// filter on the account that you want to delete from the cache.
// I take the first one here to keep the code sample short
const account = accounts[0];
msalApp.getTokenCache().removeAccount(account);

For logging out from AAD, you'll have to redirect the user to the Azure AD logout endpoint. The documentation here should explain how to craft this request.

In answer of sgonzalez, I can see the error in "accounts". This const is a Promisse:

const accounts = msalApp.getTokenCache().getAllAccounts(); // <- is a Promisse
// filter on the account that you want to delete from the cache.
// I take the first one here to keep the code sample short
const account = accounts[0];
msalApp.getTokenCache().removeAccount(account);

Correcting:

pca.getTokenCache().getAllAccounts().then((response) => {
    const account = response[0];
    pca.getTokenCache().removeAccount(account).then(() => {
         res.sendStatus(200);
    }).catch((error) => {
         res.status(500).send({error});
    });
}).catch((error) => {
    res.status(500).send(error);
});

I don't know if this is the best way to implement it, but it worked for me.

Related