代码之家  ›  专栏  ›  技术社区  ›  infodev

Microsoft Graph API令牌验证失败

  •  1
  • infodev  · 技术社区  · 6 年前

    我会在我的Angular Web应用程序中使用Microsoft Graph API。

    首先我用 msal library 当我尝试用profil登录时,我得到了这个错误

    我已将我的应用程序配置为官方 git sample

    MsalModule.forRoot({
      clientID: "Tenant ID",
      authority: "https://login.microsoftonline.com/common/",
      redirectUri: "http://localhost:4200/",
      validateAuthority : true,
      popUp: true
    }),
    

    身份验证正在工作,我得到了令牌。

    然后,当我在主页中时,我向MicrosoftGraphAPI发出第二个请求,以使用该令牌获取用户信息。

    getProfile() {
      let header= new Headers();
      let tokenid= sessionStorage.getItem('msal.idtoken'); 
      header.set('Authorization', 'Bearer ' + tokenid)
      let url ="https://graph.microsoft.com/v1.0/me/"
      return this.http.get(url,{headers:header});
    }
    

    我得到一个401未经授权的错误的响应:

    {
      "error": {
        "code": "InvalidAuthenticationToken",
        "message": "Access token validation failure.",
        "innerError": {
          "request-id": "xxxxxx",
          "date": "2018-10-09T22:58:41"
        }
      }
    }
    

    更新 :我了解到,实际上我得到的id\令牌与访问令牌不同。如何从MSAL库获取访问令牌以进行MS GRAPH API调用

    2 回复  |  直到 6 年前
        1
  •  3
  •   Michael Mainer    6 年前

    let tokenid= sessionStorage.getItem('msal.idtoken');

    变得像:

    let tokenid= sessionStorage.getItem('msal.token'); // or msal.accesstoken

    更新 (根据菲利普的评论)

    您需要选择要在应用程序中作为目标的作用域。因此,看起来您需要用户配置文件,因此您需要添加ApproveScopes属性来指定应用程序将使用的作用域:

    MsalModule.forRoot({
      clientID: "Tenant ID",
      authority: "https://login.microsoftonline.com/common/",
      redirectUri: "http://localhost:4200/",
      validateAuthority : true,
      popUp: true,
      consentScopes: ["user.read"]
    }),
    
        2
  •  5
  •   dkinzer    6 年前

    根据 the same sample 也可以附加 HttpInterceptor

    许可范围: 允许客户机表示应该同意的所需范围。作用域可以来自多个资源/端点。在这里传递scope只会同意它,在客户端实际调用API之前,不会获取任何访问令牌。如果您仅将MSAL用于登录(身份验证),则这是可选的。

    这表明使用

    内部使用 getCachedTokenInternal(scopes: Array<string>, user: User) code found here . 我不确定您是否也可以使用此方法来获取该资源的新令牌。我就用拦截器。

    您可以尝试复制访问令牌并查看它在上的外观 jwt.ms jwt.io

    对Graph有效的任何标记都应具有 观众 属于 https://graph.microsoft.com ,因此,如果您检查令牌(在jwt.ms中),它至少应该有这个值。

    "aud": "https://graph.microsoft.com",
    
        3
  •  0
  •   Faisal Mehboob    5 年前

    https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/samples/MSALAngularDemoApp

    export const protectedResourceMap:[string, string[]][]=[ ['https://graph.microsoft.com/v1.0/me', ['user.read']] ];