Microsoft Graph API 令牌验证失败

Microsoft Graph API token validation failure

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

首先我使用 msal library 建立连接 当我尝试使用我的配置文件登录时,出现此错误

我已经按照官方提到的方式配置了我的应用程序git sample

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

身份验证有效,我得到了令牌。

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

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"
    }
  }
}

我不知道为什么 MG API 不接受我的令牌,我是否使用了错误的权限 url?

UPDATE:我知道实际上我得到的是 id_token,这与访问令牌不同。如何从 MSAL 库获取访问令牌以进行 MS GRAPH API 调用?:

问题是您使用的是 id_token 而不是访问令牌:

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

变成类似:

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

更新(根据 Phillipe 的评论)

您需要 select 您希望在应用程序中定位的范围。因此,看起来您需要用户配置文件,因此您需要添加 consentScopes 属性 以指定您的应用程序将使用的范围:

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

根据 the same sample,您还可以附加一个 HttpInterceptor,它将自动将访问令牌附加到每个(外部)HTTP 调用。

通过阅读文档,我发现了以下信息。

consentScopes: Allows the client to express the desired scopes that should be consented. Scopes can be from multiple resources/endpoints. Passing scope here will only consent it and no access token will be acquired till the time client actually calls the API. This is optional if you are using MSAL for only login (Authentication).

这表明使用 HttpInterceptor 不仅可以附加访问令牌,还可以检索它。您看到的令牌可能只是您的应用程序的令牌,但不是 Graph API.

的有效令牌

它在内部使用 getCachedTokenInternal(scopes: Array<string>, user: User) 为特定范围 code found here 获取新的访问令牌。我不确定您是否也可以使用此方法为该资源获取新令牌。我只会使用拦截器。

您可以尝试复制访问令牌并查看它在 jwt.ms (a Microsoft provided JWT token viewer) or jwt.io 上的样子。

任何对 Graph 有效的标记都应该有 https://graph.microsoft.comAudience,所以如果你检查标记(在 jwt.ms 中)它至少应该有这个值。

"aud": "https://graph.microsoft.com",

确保将端点添加到资源映射配置。看到这个link: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']] ];