【发布时间】:2020-09-15 02:13:14
【问题描述】:
大家好,
我遇到了一个场景,我应该调用一个由 AZURE ACTIVE DIRECTORY 保护的 REST api。大多数代码运行良好,我也可以使用 myMSALObj.acquireTokenSilent 函数获取令牌。
当我使用该令牌发送 AJAX 调用时出现 401 错误,您可以看到以下代码
用户在我获得正确令牌的 Active Directory 中,我不知道为什么当我将该令牌发送到 rest-api 时我的 ajax 调用失败,请帮助
<script type="text/javascript">
const msalConfig = {
auth: {
clientId: "94edf294-08ae-489f-8621-c6d98009afa8",
authority: "https://login.microsoftonline.com/c483b3c4-21a6-4c93-95ea-7436cf318a68",
redirectUri: "https://localhost:44334/",
},
cache: {
cacheLocation: "sessionStorage", // This configures where your cache will be stored
storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
}
};
const myMSALObj = new Msal.UserAgentApplication(msalConfig);
function CallApi() {
// Add scopes for the id token to be used at Microsoft identity platform endpoints.
const loginRequest = {
scopes: ["User.Read"],
};
myMSALObj.loginPopup(loginRequest)
.then((loginResponse) => {
const accessTokenRequest = {
scopes: ["api://8c2b0253-f9e8-442c-bccf-b4a8bbe73b59/access_as_user"]
};
myMSALObj.acquireTokenSilent(accessTokenRequest).then((accessTokenResponse) => {
var accessToken = accessTokenResponse.accessToken;
var apiEndpoint = "https://localhost:44387/api/hello";
var bearer = "Bearer " + accessToken;
console.log("accessToken = ", accessToken);
$.ajax({
url: apiEndpoint,
type: "GET",
beforeSend: function (xhr) { xhr.setRequestHeader("Authorization", bearer) }
}).done(function (response) {
alert("SUCCESS");
console.log("response = ", JSON.stringify(response));
}).fail(function (err) {
console.error("Error Occurred");
console.log("error = ", JSON.stringify(err));
});
})
}).catch(function (error) {
console.log(error);
});
}
</script>
【问题讨论】:
-
您是否将您的 API 暴露给客户端应用注册?
-
使用jwt.ms 解析您的令牌并提供屏幕截图。您必须确保客户端应用程序请求的范围与令牌的预期接收者一致。检查你的
aud,确保是你要调用的api,401的原因你可能使用了错误的token或者你使用了不属于该api的token来调用api。跨度> -
@Purushothaman 我看不出您的代码有任何问题。我认为问题仍然出现在您的 apiEndpoint 中。您的 apiEndpoint 是自定义 api 吗?确保它是您的令牌接收者。
-
您可以在此文档中找到在 web api 中实现身份验证和授权的详细信息。 docs.microsoft.com/en-us/azure/active-directory/develop/…
标签: javascript azure-active-directory http-status-code-401 rest