我正在为我想要保护的一个非常简单的 web 应用程序实现 OAuth2 隐式授权流。我正在使用 MSAL 来做到这一点。我遇到的问题是,当我从浏览器尝试 URL 时,它会将我带到组织登录页面,然后将我带到重定向 URI。
但是,当我从应用程序调用它时,我收到了 CORS 错误。堆栈跟踪如图所示
Access to XMLHttpRequest at '**********/oauth2/authorize/.well-known/openid-configuration' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
index.js:99 ClientAuthError: Error: could not resolve endpoints. Please check network and try again. Details: function toString() { [native code] }
at ClientAuthError.AuthError [as constructor] (webpack:///./node_modules/msal/lib-es6/error/AuthError.js?:26:28)
at new ClientAuthError (webpack:///./node_modules/msal/lib-es6/error/ClientAuthError.js?:111:28)
at Function.ClientAuthError.createEndpointResolutionError (webpack:///./node_modules/msal/lib-es6/error/ClientAuthError.js?:121:16)
at eval (webpack:///./node_modules/msal/lib-es6/UserAgentApplication.js?:455:125)
XHRClient.js:43 GET ***********/authorize/.well-known/openid-configuration net::
我的代码如下所示
import $ from "jquery";
import 'bootstrap';
import * as Msal from "msal";
window.addEventListener("load", (event) => {
const msalConfig = {
auth: {
clientId: “***************”,
authority: "https://login.microsoftonline.com/<tenant-id>/oauth2/v2.0/authorize"
},
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
forceRefresh: false // Set this to "true" to skip a cached token and go to the server to get a new
}
};
const loginRequest = {
scopes: ["openid"],
};
console.log(new Msal.UserAgentApplication(msalConfig));
const myMSALObj = new Msal.UserAgentApplication(msalConfig);
myMSALObj.handleRedirectCallback(authRedirectCallBack);
function authRedirectCallBack(error, response) {
if (error) {
console.log(error);
} else {
console.log(response);
}
}
myMSALObj.loginPopup(loginRequest)
.then(loginResponse => {
console.log('id_token acquired at: ' + new Date().toString());
if (myMSALObj.getAccount()) {
console.log(myMSALObj.getAccount());
// showWelcomeMessage(myMSALObj.getAccount());
}
}).catch(function (error) {
console.log(error);
});
}