![](/img/trans.png)
[英]How to retrieve access_token from Azure Active Directory (AAD) Web API
[英]How to Get a valid access token for my API and Microsoft Graph from Azure Active Directory?
我正在尝试设置一个 spa javascript 应用程序,该应用程序将用户登录到我们的 azure 活动目录租户,然后从 microsoft graph 检索配置文件信息并调用用 c# 核心(我的 API)编写的 azure 函数。
我为我的网站和 azure 活动目录中的 api 设置了单独的应用程序注册。
我正在 javascript spa 网站中使用 MSAL.js 库,并且我正在使用较新的 microsoft identity / v2.0 端点。
SPA 应用程序按预期登录活动目录,并能够使用访问令牌调用图表以获取配置文件信息。 在我的 azure 函数中,我验证了令牌,但失败并显示错误“IDX10511:签名验证失败。尝试过的密钥:.....”
现在,如果我在请求令牌时从范围中删除 Microsoft 图形,我会得到一个令牌,该令牌在传递给 azure 函数时验证得非常好,但我无法再在 spa 应用程序中检索配置文件数据?
我如何让两者都工作?
还值得注意的是,我使用 jwt.io 测试了令牌,并且在使用图形时也无法验证签名。
这是我获取令牌的方式:
var msalConfig = {
auth: {
redirectUri: window.location.origin, // forces top level instead of specific login pages - fixes deep link issues.
clientId: "Client ID of the website app", //This is your client ID
authority:
"https://login.microsoftonline.com/my-tennant-guid" //This is your tenant info
},
cache: {
cacheLocation: "localStorage",
storeAuthStateInCookie: true
}
};
const msalUserAgent = new Msal.UserAgentApplication(msalConfig);
var requestObj = {
scopes: ["User.Read", "api://MyApi/Access"]
};
//when the spa starts up I login using redirects
msalUserAgent.loginRedirect(requestObj);
//then before calling an api I request a token using this method
acquireTokenSilent() {
var promise = msalUserAgent.acquireTokenSilent(requestObj);
return promise;
},
尝试在acquireTokenSilent() 函数中将scopes: ["User.Read"]
指定为scopes: ["User.Read"]
。 由于访问令牌仅对一个 API 有效。 如果您需要两个,请使用不同的范围两次调用acquireTokenSilent。
登录时可以为两个 API 指定范围,但在获取令牌时则不能。 令牌具有指定目标 API 的受众。 因此,您不能将一个 API 的令牌用于另一个 API。 这就是为什么它只对一个 API 有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.