首页 > 解决方案 > ADAL SPFx getCachedUser 始终为空

问题描述

我们有一个 SPFx Web 部件运行良好,但即使用户在点击包含 SPFx Web 部件的页面时已经登录到 Office 365 - getCachedUser 对象始终为空。这会强制重定向登录,它会立即自动重定向回我们的应用程序页面。

我们最初使用纯 JavaScript 的 PoC 从未这样做过,但 SPFx Web 部件总是在第一次点击时重定向。

有没有人看到并修复了这种行为?我们应该在 Authentication 包装器中寻找什么?

这是我们的代码示例:

import * as AuthenticationContext from 'adal-angular';
import '../WebPartAuthenticationContext';

constructor(props) {
    super(props);
    this.state = {
      detailModal: false,
      item: null,
      columns: [],
      rows: [],
      titleFilter: null,
      filterBy: 'givenName'
    };

    const config: IAdalConfig = {
      tenant: this.props.tenant,
      clientId: this.props.clientId,
      postLogoutRedirectUri: window.location.origin
    };
    config.webPartId = '<GUID>';
    config.popUp = false;
    config.callback = (error: any, token: string): void => {};
    this.authCtx = new AuthenticationContext(config);
    this.authCtx.handleWindowCallback();
    AuthenticationContext.prototype._singletonInstance = undefined;
}

private getRealItemsByAzureGraph(searchFor: string){
    var params = {
      'api-version': '1.6',
      '$filter': searchFor, 
      '$top' : '999'
    }; 
    var baseURL = 'https://graph.windows.net/myorganization/users?' + jquery.param(params);

    var user = this.authCtx.getCachedUser();
    if (user) {
      this.authCtx.acquireToken("https://graph.windows.net", (error, accessToken) => {
        if (error || !accessToken) { console.log(error); } 
        else {
          jquery.ajax({
            type: 'GET',
            url: baseURL,
            dataType: "json",
            headers: {
              'Authorization': 'Bearer ' + accessToken,
              'Accept': 'application/json'
            }
          }).done((data) => {
            var res = [];
            data.value.forEach((itm) => {
              if (itm.surname && itm.mail && itm.givenName && this.notInKeywords(itm)){
                if (this.props.showGuestUsers) {
                  res.push(itm);
                } else {
                  if (itm.userType !== "Guest") {
                    res.push(itm);
                  }
                }
              }
            });
            this.setState(
              {
                rows: res,
              }
            );
          }).fail((err) => {
            console.log(err.responseText);
          });
        }
      });
    } else {
      this.authCtx.login();
    }
}

这段代码(和其他支持代码)效果很好,即使用户登录,我们也无法绕过重定向。getCachedUser 方法始终为空/未定义。

标签: adalspfx

解决方案


推荐阅读