【发布时间】:2020-11-05 10:59:22
【问题描述】:
我想访问一个正在运行的受保护 Web API。在 Azure 中,应用注册是:
- 具有对 Web API 的租户管理员权限的 SPA
- Web API 没有租户管理员权限,因此为其 id 请求令牌将返回“应用程序需要访问资源的权限”错误
我正在尝试获取 Web API 的不记名令牌。问题是它不适用于 MSAL,但它确实适用于 ADAL。
这是我的“SPA”的 ADAL vanilla JS 代码:
window.config = {
clientId: 'SPA client id',
tenant: 'Tenant id',
redirectUri: 'http://localhost:3000',
extraQueryParameter: 'nux=1',
popUp: true
};
var authContext = new AuthenticationContext(config);
function getToken(){
var user = authContext.getCachedUser();
if (!user) {
authContext.login();
return;
}
var cachedToken = authContext.getCachedToken(window.config.endpoints.prod);
if (!cachedToken) {
authContext.acquireToken("Web API Client Id", function(error, token) {
console.log(error);
});
}
console.log(cachedToken);
var t = document.getElementById("token");
t.innerText = cachedToken;
};
如果我在 Postman 中复制令牌并发出请求,它将起作用。
MSAL代码如下:
const msalConfig = {
auth: {
clientId: "SPA client id",
authority: "https://login.microsoftonline.com/Tenant id"
}
};
const loginRequest = {
scopes: ["copied the scope of SPA from the Expose API"],
redirectUri: "http://localhost:3000/"
};
const myMSALObj = new Msal.UserAgentApplication(msalConfig);
myMSALObj.loginPopup(loginRequest).then(handleResponse).catch(function (error) { console.log(error);});
var tokenRequest = {
scopes: ["Copied scope from the Web API expose API section"],
};
if (!token) {
myMSALObj.acquireTokenPopup(tokenRequest)
.then(response => {
console.log(response);
setTimeout(function () {
token = response.accessToken;
});
console.log(token);
现在我注意到有一点不同:ADAL 允许我在调用 acquireToken 方法时传递 Web Api 的客户端 ID,而 MSAL 不允许。找不到任何文档,但我认为它是从 Application Id Uri 解决的。
第二个区别在于令牌声明 aud:
- ADAL aud 是 Web API 客户端 ID
- MSAL aud 是 Web API 应用程序 ID Uri
【问题讨论】:
-
MSAL报错是什么?我试试the sample,效果很好。
-
感谢您试用。当我在范围 [] 中使用 AppId/范围并且应用注册具有 AppIdUri/范围形式的范围时,MSAL 似乎有效。我不知道为什么 AppIdUri 不起作用,但我认为 API 被配置为只接受它自己的 App Id 而不是它的 App Id Uri。为什么它的范围(在公开 API 部分)是这样写的?我不知道。
标签: azure azure-active-directory