gpt4 book ai didi

javascript - Azure通过javascript获取访问 token

转载 作者:行者123 更新时间:2023-12-03 02:26:19 26 4
gpt4 key购买 nike

我正在尝试从 Azure 获取访问 token 。我正在关注this教程,但问题是那家伙正在使用 postman 。它在 postman 中也适用于我,但在 javascript 中失败,我不明白为什么。

  function getAccessToken() {
fetch(`${loginUrl}${tenantId}/oauth2/token`, {
method: "POST",
body: JSON.stringify({
grant_type: "client_credentials",
client_id: clientId,
client_secret: clientSecret,
resource: resource,
})
})
.then((response) => {
console.log(JSON.stringify(response));
})
.catch((err) => {
console.log(JSON.stringify(err));
});
}

凭据良好,即 clientId、secret、tenantid 等。我也在 PowerShell 中尝试过,它有效:

Invoke-RestMethod `
-Uri "$loginUrl$tenantId/oauth2/token" `
-Method Post `
-Body @{"grant_type"="client_credentials"; "resource" = $resource; "client_id" = $clientId; "client_secret" = $clientSecret }

但是在 js 上我收到以下错误:

Access to fetch at 'https://login.microsoftonline.com/myTenantId/oauth2/token' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

目前我正在 HTML 文件中运行此脚本以进行测试。

最佳答案

如果我们在 HTML 页面中直接从与您的网站不同的域调用其余 api,我们将遇到 CORS 问题。这是出于安全原因。更多详情请引用here .

因此,如果您想在 HTML 页面中获取 Azure AD token ,我建议您使用包 msaljs 来实现隐式流程来获取 token 。该软件包修复了 cors 问题。具体操作方法请引用here .

此外,如果您仍然想使用客户端凭据流来获取 HTML 页面中的 token 。你有两个选择。一种选择是使用代理服务器。代理充当客户端和服务器之间的中介。后续详细信息请引用blog .

关于javascript - Azure通过javascript获取访问 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66734033/

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