我在节点应用程序中使用
@azure/msal-node
包,使我的用户能够使用其 AzureAD 凭据登录。登录和获取会话令牌工作正常,但我找不到使会话无效/注销用户的方法 - 我是否忽略了这里明显的东西?
仅供参考,以下是我获取代币的方式:
// 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);
}
在重定向处理程序中,我正在这样做:
const tokenResponse = await msalApp.acquireTokenByCode({
code: request.query.code,
scopes: ['user.read'],
redirectUri: BASE_URL + '/msal-redirect'
});
然后我使用该令牌来显示登录的用户等。
我缺少的是类似
msalApp.logout()
的东西 - 我在这里没有看到什么?
遗憾的是,MSAL 目前不包含
msalApp.logout()
API。相反,您必须手动实施这些步骤。
注销操作将包含多个步骤:
要从 msal 应用程序缓存中删除帐户和令牌,您可以执行以下操作:
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);
要从 AAD 注销,您必须将用户重定向到 Azure AD 注销端点。 此处的文档应该解释如何制定此请求。
在sgonzalez的回答中,我可以看到“帐户”中的错误。这个 const 是一个 Promise:
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);
更正:
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);
});
我不知道这是否是实现它的最佳方法,但它对我有用。
MSAL 不会公开帐户。您可以尝试以下方法:
logout(options = {}) {
return (req, res, next) => {
const accessToken = req.session?.accessToken
if (accessToken) {
let logoutUri = `${this.msalConfig.auth.authority}/oauth2/v2.0/`;
if (options.postLogoutRedirectUri) {
logoutUri += `logout?post_logout_redirect_uri=${options.postLogoutRedirectUri}`;
}
res.redirect(logoutUri);
} else {
return res.redirect("/login");
}
}
}
这对我有用。这将带您退出 Microsoft 页面,您可以选择要从中注销的帐户。