[英]Make API call to Azure API App in JavaScript with Active Directory authentication
[英]401 Error - Call REST API secured with AZURE Active Directory (JavaScript Client)
大家好,
我有一个场景,我应该调用一个由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>
我的不好,我的startup.cs文件中缺少以下调用
app.UseAuthentication();
谢谢你们的帮助
特别是 - @Carl Zhao、@Purushothaman @Rass Masood
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.