gpt4 book ai didi

javascript - OAuth2 访问源错误

转载 作者:太空宇宙 更新时间:2023-11-04 16:22:06 25 4
gpt4 key购买 nike

我从 OAuth2 服务器请求授权代码。我的目的是使用我的微软应用程序授权用户。引用Document

我尝试调用电话:

function httpGet(){
var theUrl = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id="client_id"&response_type=code&redirect_uri="redirect_uri"&response_mode=query&resource=https%3A%2F%2Fservice.contoso.com%2F&state=12345";

var req = new XMLHttpRequest();
req.open('GET', theUrl, true);
req.onreadystatechange = function() {
if (req.readyState === 4) {
if (req.status >= 200 && req.status < 400) {
console.log(req.responseText)
} else {
console.log("error")
}
}
};
req.send();
}

但这会产生以下错误:

No 'Access-Control-Allow-Origin' header is present on the requested resource.

然后我添加 req.setRequestHeader("Access-Control-Allow-Origin", "*");

但它给出了以下错误:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

最佳答案

要将 AAD 集成到 javascript 中,我们建议您使用 azure-activedirectory-library-for-js这是一个 JavaScript 库,供前端轻松集成 AAD。

在使用 ADAL for JS 之前,有两个选项需要注意:

以下是从 Microsoft Graph 获取访问 token 的代码示例:

<script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.0.10/js/adal.min.js"></script>

<body>
<a href="#" onclick="login();">login</a>
<a href="#" onclick="getToken()">access token</a>
</body>
<script type="text/javascript">
var configOptions = {
tenant: "<tenant_id>", // Optional by default, it sends common
clientId: "<client_id>",
postLogoutRedirectUri: window.location.origin,
}
window.authContext = new AuthenticationContext(configOptions);

var isCallback = authContext.isCallback(window.location.hash);
authContext.handleWindowCallback();

function getToken(){
authContext.acquireToken("https://graph.microsoft.com",function(error, token){
console.log(error);
console.log(token);
})
}
function login(){
authContext.login();
}
</script>

关于javascript - OAuth2 访问源错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40543391/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com