Azure 通过 javascript 获取访问令牌

Azure get access token via javascript

我正在尝试从 Azure 获取访问令牌。我正在学习 this 教程,但问题是那个人在使用邮递员。它也适用于邮递员,但它在 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令牌,我建议你使用包msaljs来实现隐式流来获取令牌。该软件包已修复 cors 问题。具体操作方法请参考here.

此外,如果您仍想使用客户端凭据流在 HTML 页面中获取令牌。你有两个选择。一种选择是使用代理服务器。代理充当客户端和服务器之间的中介。日后详情请参考blog.