从 Javascript returns 执行 AWS Signv4 HTTP API 403 错误

Executing AWS Signv4 HTTP API from Javascript returns 403 error

我正在为 AWS API 中的 HTTP API 开发 Javascript(浏览器)客户端 API Gateway.The API 使用 IAM授权人。在我的 Javascript 应用程序中,我通过 Cognito 身份池(开发人员身份)登录。接下来,我使用 AWS.CognitoIdentityCredentials.

将 OpenID 令牌转换为访问密钥 ID、秘密访问密钥和 session 令牌

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

我还尝试了 JWT 授权方,传递从 Cognito 身份池接收的 OpenID 令牌(使用 http://cognito-identity.amazon.com 作为提供者)。这样做时我收到错误:www-authenticate 响应 header.

中的 Bearer scope="" error="invalid_token" error_description="unable to decode "n" from RSA public key"

非常感谢。

        // 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()));
         });

经过一些调试和网络搜索,我找到了解决方案。生成正确的签名似乎需要 'host' header:

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

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