我目前正在尝试使用 webapi 开发 SPA 应用程序,我正在使用 msal 进行登录。流程是用户登录,获取 idtoken(用于授权我的 api),使用 acquiretokensilent 方法获取访问令牌(用于图形 api)。我通过在范围中传递 clientID 使用 acquiretokensilent 在一个小时之前更新了 idToken。但是在 idToken 过期后我仍然注销了。我看到它没有在浏览器存储中刷新。
所以我的问题是,无论如何我可以更新 id Token 并让用户保持登录状态吗?任何帮助都会很棒。
acquireTokenSilent(scopes: Array, authority?: string, user?: User, extraQueryParameters?: string): Promise - 用于从缓存中获取令牌。 MSAL 将返回 缓存的令牌(如果未过期) 或者它会向 STS 发送请求以使用隐藏的 iframe 获取访问令牌。要更新 idToken,clientId 应该作为范围数组中的唯一范围传递。
https://github.com/AzureAD/microsoft-authentication-library-for-js/wiki/Public-APIs
当您尝试刷新您的令牌时,您实际上是在从缓存中检索它,因为它还没有过期吗?
很遗憾,AAD 不支持刷新 ID 令牌。只能刷新访问令牌。请参阅此处:https://azure.microsoft.com/en-us/documentation/articles/active-directory-protocols-oauth-code/#refreshing-the-access-tokens。此外,如果您想了解更多关于token的信息,请参考文档.
您可以使用 sso,通过它您可以在这里获得一个新的 id_token。
如果token和current之间的时间差超过5分钟那么它会从sso获取新的token 请注意,这将在您进行活动会话时起作用。
this.adalSvc.instance.acquireTokenSilent(tokenRequest)
.then( (token: any) => {
const rem_id_token_Time = this.diff_minutes(new Date(token.idTokenClaims.exp * 1000), new Date());
console.log(rem_id_token_Time);
if ( rem_id_token_Time > 5) {
this.shared.refreshToken(token.idToken, token.accessToken);
resolve (token.accessToken);
} else {
const ssoRequest = { loginHint: token.account.username };
this.adalSvc.instance.ssoSilent(ssoRequest)
.then(() => {
this.shared.refreshToken(token.idToken, token.accessToken);
resolve (token.accessToken);
})
.catch(error => {
reject(error);
});
}
}
diff_minutes(dt2, dt1) {
var diff =(dt2.getTime() - dt1.getTime()) / 1000;
diff /= 60;
return Math.abs(Math.round(diff));
}