You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 14:48:05