【问题标题】:Executing AWS Signv4 HTTP API from Javascript returns 403 error从 Javascript 执行 AWS Signv4 HTTP API 返回 403 错误
【发布时间】:2020-10-21 07:23:28
【问题描述】:

我正在为 AWS API Gateway 中的 HTTP API 开发 Javascript(浏览器)客户端。API 使用 IAM 授权方。在我的 Javascript 应用程序中,我通过 Cognito 身份池(开发人员身份)登录。接下来,我使用 AWS.CognitoIdentityCredentials 将 OpenID 令牌转换为访问密钥 ID、秘密访问密钥和会话令牌。

然后我想使用这些凭据进行 API 调用,使用下面的代码。我看到调用正在执行,但我得到一个 HTTP/403 错误。答复没有进一步说明原因。我很感激所有帮助了解出了什么问题。禁用 IAM 授权方时,HTTP API 运行良好。

我还尝试了 JWT 授权方,传递从 Cognito 身份池接收的 OpenID 令牌(使用 http://cognito-identity.amazon.com 作为提供者)。这样做时,我收到错误:Bearer scope="" error="invalid_token" error_description="unable to decode "n" from RSA public key"www-authenticate 响应标头中。

非常感谢。

        // Credentials will be available when this function is called.
        var accessKeyId = AWS.config.credentials.accessKeyId;
        var secretAccessKey = AWS.config.credentials.secretAccessKey;
        var sessionToken = AWS.config.credentials.sessionToken;

        let test_url = 'https://xxxxxxx.execute-api.eu-central-1.amazonaws.com/yyyyyy';

        var httpRequest = new AWS.HttpRequest("https://" + test_url, "eu-central-1");
        httpRequest.method = "GET";

        AWS.config.credentials = {
            accessKeyId: accessKeyId,
            secretAccessKey: secretAccessKey,
            sessionToken: sessionToken
        }



        var v4signer = new AWS.Signers.V4(httpRequest, "execute-api");
        v4signer.addAuthorization(AWS.config.credentials, AWS.util.date.getDate());

         fetch(httpRequest.endpoint.href , {
            method: httpRequest.method,
            headers: httpRequest.headers,
            //body: httpRequest.body
        }).then(function (response) {
             if (!response.ok) {
                 $('body').html("ERROR: " + JSON.stringify(response.blob()));
                 return;
             }
             $('body').html("SUCCESS: " + JSON.stringify(response.blob()));
         });

【问题讨论】:

    标签: amazon-web-services aws-api-gateway aws-amplify


    【解决方案1】:

    经过一些调试和网络搜索,我找到了解决方案。生成正确的签名似乎需要一个“主机”标头:

    httpRequest.headers.host = 'xxxxxxx.execute-api.eu-central-1.amazonaws.com'
    

    添加此主机头后,API 调用成功。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-18
      • 2017-06-19
      • 1970-01-01
      • 2019-01-29
      • 2019-04-29
      • 2021-06-17
      • 2017-09-27
      相关资源
      最近更新 更多