javascript - 使用 Azure AD 和 SPA 获取令牌失败
问题描述
我正在开发我的网络应用程序,它是一个单页应用程序。我想将它与 Azure Aactive Directory 集成以登录用户并调用 microsoft graph API。我正在关注此文档:https ://docs.microsoft.com/en-us/azure/active-directory/develop/v2-protocols-oidc 。
但是当我尝试获取ID令牌或访问令牌时似乎并不那么顺利,我总是得到一个错误:
blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
。我该如何解决?我的方向是否正确?谢谢!
解决方案
正如超级巨星@GauravMantri 提到的,如果您正在开发SPA,您应该使用它MSAL.js
来登录用户并获取令牌。在这里直接调用 REST API 不起作用。
只需尝试以下 .html 代码即可登录用户并获取 Microsoft Graph API 的访问令牌:
<html>
<head>
<meta charset="utf-8">
<title>Azure AD test</title>
<script type="text/javascript" src="https://alcdn.msauth.net/lib/1.4.4/js/msal.min.js"></script>
</head>
<body>
<div >
<button id="SignIn" onclick="signIn()">Sign in</button><br/>
<div id="WelcomeMessage"/><br/>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
var clientAppID = "<your public client Azure AD APP ID>"
var tenantID = "<your tenant ID>"
var demoScops = {
scopes:["https://graph.microsoft.com/User.Read"]
}
var msalConfig = {
auth: {
clientId: clientAppID,
authority: "https://login.microsoftonline.com/" + tenantID
},
cache: {
cacheLocation: "localStorage",
storeAuthStateInCookie: true
}
};
var myMSALObj = new Msal.UserAgentApplication(msalConfig);
myMSALObj.handleRedirectCallback(authRedirectCallBack);
function signIn() {
myMSALObj.loginPopup(demoScops).then(function (loginResponse) {
console.log(loginResponse);
initPage();
}).catch(function (error) {
console.log(error);
});
}
function initPage(){
showWelcomeMessage();
callGraphApi();
}
function showWelcomeMessage() {
var divWelcome = document.getElementById('WelcomeMessage');
divWelcome.innerHTML = 'welcome! ' + myMSALObj.account.userName + '</br>';
var loginbutton = document.getElementById('SignIn');
loginbutton.innerHTML = 'sign out';
loginbutton.setAttribute('onclick', 'signOut();');
}
function callGraphApi(){
myMSALObj.acquireTokenSilent(demoScops).then(function (tokenResponse) {
var accessToken = tokenResponse.accessToken;
$.ajax({
url: "https://graph.microsoft.com/v1.0/me",
type: "GET",
async: false,
beforeSend: function(xhr){xhr.setRequestHeader('Authorization', 'Bearer '+ accessToken);},
success: function(data) {
console.log(data)
}
});
}).catch(function (error) {
console.log(error);
})
}
function authRedirectCallBack(error, response) {
if (error) {
console.log(error);
}
}
function requiresInteraction(errorCode) {
if (!errorCode || !errorCode.length) {
return false;
}
return errorCode === "consent_required" ||
errorCode === "interaction_required" ||
errorCode === "login_required";
}
var ua = window.navigator.userAgent;
var msie = ua.indexOf('MSIE ');
var msie11 = ua.indexOf('Trident/');
var msedge = ua.indexOf('Edge/');
var isIE = msie > 0 || msie11 > 0;
var isEdge = msedge > 0;
var loginType = isIE ? "REDIRECT" : "POPUP";
if (loginType === 'POPUP') {
if (myMSALObj.getAccount()) {
initPage()
}
}
else if (loginType === 'REDIRECT') {
document.getElementById("SignIn").onclick = function () {
myMSALObj.loginRedirect(requestObj);
};
if (myMSALObj.getAccount() && !myMSALObj.isCallback(window.location.hash)) {
initPage()
}
} else {
console.error('Please set a valid login type');
}
function signOut() {
window.localStorage.clear();
myMSALObj.logout();
}
</script>
</html>
如果您还有其他问题,请告诉我。
推荐阅读
- python - Python3.8 Import Error No module name tqdm found
- python - Python-Selenium:如何抓取表格中的一些特定元素并将其从小数转换为小数
- r - 如何计算数据组合的出现次数并保存在R中的矩阵中?
- c# - 找到发射弹丸的角度以到达特定点
- java - Apache POI java.lang.NoClassDefFoundError 读取 excel 文件
- go - 如何使用 Golang Link A Contaxt Form 发送电子邮件
- javascript - 改变方向并在数组中移动元素
- sql-server - 查询失败 --- select count(*) with order by got sqlserver error 8127
- vega-lite - 使用选择时如何动态更改标题?
- azure - 具有多个后端的 Azure API 管理