使用adal-angular包adal.js的authenticationContext获取Microsoft Graph Token报错
报错原因
- 核心问题是
handleWindowCallback处理登录回调的逻辑结束后,没有校验登录是否真的成功,就直接调用了acquireToken获取Graph资源令牌。adal的令牌缓存写入、登录态校验都需要等回调完全处理完成,你当前的调用时机过早,此时本地还没有有效的用户登录缓存,所以adal判定用户未登录抛出错误。 - 次要排查点:如果确认调用时机没问题,还需要检查Azure AD应用注册是否配置了Microsoft Graph的对应权限,以及adal初始化配置的
clientId、tenant、redirectUri参数是否和应用注册的配置完全一致。
解决方案
首先修改initialize方法的回调分支逻辑,增加登录状态校验,确认无错误且用户存在后再获取Graph令牌:
initialize() { this.authenticationContext = new AuthenticationContext(config); return new Promise((resolve, reject) => { if (this.authenticationContext.isCallback(window.location.hash) || window.self !== window.top) { this.authenticationContext.handleWindowCallback(); // 新增:先判断回调是否有登录错误 const loginError = this.authenticationContext.getLoginError(); if (loginError) { reject(loginError); this.signIn(); return; } let user = this.authenticationContext.getCachedUser(); if (user) { // 确认用户存在再获取Graph令牌 this.graphToken(this.authenticationContext); resolve(user); } else { reject(new Error('无有效登录用户')); this.signIn(); } } else { let user = this.authenticationContext.getCachedUser(); if (user) { // 非回调场景如果用户已登录,也可以在这里补充调用graphToken this.graphToken(this.authenticationContext); resolve(user); } else { this.signIn(); } } }); }
其次可以优化graphToken方法的错误处理,针对需要登录的报错增加重定向获取令牌的兜底逻辑:
graphToken(authctx) { authctx.acquireToken('https://graph.microsoft.com', function (error, token) { if (error || !token) { console.log(error + ":::error is here"); // 报错需要登录时,触发重定向获取对应资源的令牌 if (error === 'User Login is required') { authctx.acquireTokenRedirect('https://graph.microsoft.com'); } return; } console.log(token + "graph token"); }) }
内容的提问来源于stack exchange,提问作者sshweta7
相关产品推荐
相关产品推荐

