[经典JavaScript通过msal.js调用Graphi API

问题描述 投票:0回答:1

我正在尝试通过msal.js进行静默登录,然后尝试调用图形api,但始终会出现403错误。当我通过jwt.ms解密访问令牌时,我可以看到观众是正确的,但作用域显示错误。希望有人能帮助我。

我的代码

let config = {
    auth: {
      clientId: _spPageContextInfo.spfx3rdPartyServicePrincipalId,
      authority: `https://login.microsoftonline.com/${_spPageContextInfo.aadTenantId}`,
      redirectUri: 'https://xxx.sharepoint.com/sites/xxx-Dev/Pages/myportal.aspx',
      validateAuthority: false,
      postLogoutRedirectUri: window.origin,
    },
    cache: {
      cacheLocation: 'localStorage',
      storeAuthStateInCookie: true
    }
  }

  let myMSALObj = new Msal.UserAgentApplication(config)
  let graphConfig = {
    graphGroupEndpoint: "https://graph.microsoft.com/v1.0/groups"
  }

  let request = {
    scopes: ["https://graph.microsoft.com/.default"]
  }


  myMSALObj.handleRedirectCallback(response => { console.log(response) });
  //const idTokenScope = { scopes: [_spPageContextInfo.spfx3rdPartyServicePrincipalId] }

  const handleError = (error) => {
    if (error.errorCode === 'consent_required'
      || error.errorCode === 'interaction_required'
      || error.errorCode === 'login_required') {
      //myMSALObj.loginRedirect(idTokenScope);
      myMSALObj.loginRedirect(request);
      return;
    }
    throw error;
  };

  const getToken = () => {
    const date = new Date();
    const user = myMSALObj.getAccount();
    if (!user) {
      //myMSALObj.loginRedirect(idTokenScope);
      myMSALObj.loginRedirect(request);
      return;
    }
    //myMSALObj.acquireTokenSilent(idTokenScope).then(response => {
    myMSALObj.acquireTokenSilent(request).then(response => {
      console.log(`${date.toLocaleTimeString()}`, response.accessToken);
      callMSGraph(graphConfig.graphGroupEndpoint, response.accessToken, graphAPICallback)
    }).catch(handleError);
  }
  getToken()

  function callMSGraph(theUrl, accessToken, callback) {
    var xmlHttp = new XMLHttpRequest()
    xmlHttp.onreadystatechange = function () {
      if (this.readyState == 4 && this.status == 200)
        callback(JSON.parse(this.responseText))
    }
    xmlHttp.open("GET", theUrl, true)
    xmlHttp.setRequestHeader('Authorization', 'Bearer ' + accessToken)
    xmlHttp.send()
  }
  function graphAPICallback(data) {
    document.write(JSON.stringify(data, null, 2))
  }

我的解码令牌enter image description here

我的应用权限enter image description here

microsoft-graph sharepoint-online azure-ad-graph-api msal msal.js
1个回答
0
投票

有两种权限:一种是应用程序权限,另一种是委托权限。 “ https://graph.microsoft.com/.default”用于应用程序权限。

enter image description here

通过浏览器进行交互式签名时,系统会要求您提供凭据。这样,您将获得自己的访问令牌,该令牌具有委派权限。我们称其为OAuth 2.0 authorization code flow

但是,由于您没有在请求范围内设置任何必需的委派权限,因此,Azure AD只会向您返回具有基本委派权限的访问令牌(openid,通过电子邮件发送配置文件)。


顺便说一下,如果您只想获取具有应用程序权限的访问令牌。您只需要使用OAuth 2.0 client credentials flow即可获得令牌。

© www.soinside.com 2019 - 2024. All rights reserved.