我会在我的 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
}),
身份验证有效,我得到了 token 。
然后,当我在主页时,我向 Microsoft Graph API 发出第二个请求,以使用该 token 获取用户信息。
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 不接受我的 token ,我是否使用了错误的权限 url?
更新:我了解到实际上我得到的 id_token 不同于访问 token 。如何从 MSAL 库获取访问 token 以进行 MS GRAPH API 调用?:
最佳答案
根据 the same sample您还可以附上 HttpInterceptor
这将自动将访问 token 附加到每个(外部)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
不仅附加访问 token ,而且还检索它。您看到的 token 可能只是您的应用程序的 token ,但不是 Graph API 的有效 token 。
在内部它使用 getCachedTokenInternal(scopes: Array<string>, user: User)
为特定范围获取新的访问 token code found here .我不确定您是否也可以使用此方法为该资源获取新 token 。我只会使用拦截器。
您可以尝试复制访问 token 并查看它在 jwt.ms 上的样子(Microsoft 提供的 JWT token 查看器)或 jwt.io .
任何对 Graph 有效的标记都应该有 https://graph.microsoft.com
的Audience ,所以如果您检查 token (在 jwt.ms 中),它至少应该有这个值。
"aud": "https://graph.microsoft.com",
关于javascript - Microsoft Graph API token 验证失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52730511/