AWS S3 - 我们计算的请求签名与您提供的签名不匹配。检查您的密钥和签名方法

新手上路,请多包涵

我正在尝试使用从 aws sdk 生成的预签名 url 将图像上传到 s3。

 router.get('/upload-url', async(req, res) => {
    try {

        AWS.config.update({
            secretAccessKey: process.env.AWS_SECRET_ACCESS,
            accessKeyId: process.env.AWS_ACCESS_KEY,
            region: 'ap-southeast-1'

        });

        const s3 = new AWS.S3();
        var params = { Bucket: process.env.bucket_name, Key: 'products', ContentType: 'image/jpeg' };
        s3.getSignedUrl('putObject', params, function(err, url) {
            if (err) {
                throw (err)
            }
            res.status(200).send({ link: url })
        })

    } catch (err) {
        res.status(400).send({ message: err.message })
    }
})

使用上面的返回 url,当我尝试访问它时出现错误

<Error>
<script class="__REQUESTLY__SCRIPT">(function(namespace) { window[namespace] = window[namespace] || {}; window[namespace].responseRules = {}; let open = XMLHttpRequest.prototype.open; XMLHttpRequest.prototype.open = function(method) { this.addEventListener('readystatechange', function() { if (this.readyState === 4 && window[namespace].responseRules.hasOwnProperty(this.responseURL)) { const responseRule = window[namespace].responseRules[this.responseURL]; const {response, id} = responseRule; const responseType = this.responseType; let customResponse; customResponse = response.type === 'code' ? responseRule.evaluator({ method, url: this.responseURL, requestHeaders: this.requestHeaders, requestData: this.requestData, responseType: this.responseType, response: this.response }) : response.value; Object.defineProperty(this, 'response', { get: function () { if (response.type === 'static' && responseType === 'json') { return JSON.parse(customResponse); } return customResponse; } }); if (responseType === '' || responseType === 'text') { Object.defineProperty(this, 'responseText', { get: function () { return customResponse; } }); } window.postMessage({ from: 'requestly', type: 'response_rule_applied', id }, window.location.href); } }, false); open.apply(this, arguments); }; let send = XMLHttpRequest.prototype.send; XMLHttpRequest.prototype.send = function(data) { this.requestData = data; send.apply(this, arguments); }; let setRequestHeader = XMLHttpRequest.prototype.setRequestHeader; XMLHttpRequest.prototype.setRequestHeader = function(header, value) { this.requestHeaders = this.requestHeaders || {}; this.requestHeaders[header] = value; setRequestHeader.apply(this, arguments); } })('__REQUESTLY__')</script>
<Code>SignatureDoesNotMatch</Code>
<Message>The request signature we calculated does not match the signature you provided. Check your key and signing method.</Message>
<AWSAccessKeyId>DHAWUIHDUIAWHDAWUI</AWSAccessKeyId>
<StringToSign>GET 1594960145 /bucketname/products</StringToSign>
<SignatureProvided>oD2y%2Ftv04ernxLiNdMAETiebi1KXY%3D</SignatureProvided>
<StringToSignBytes>47 45 54 0a 0a 0a 31 35 30 34 39 36 30 31 34 35 0a 2f 64 65 76 2e 6b 6f 6c 2e 73 68 6f 70 2f 70 70 6f 64 75 63 74 73</StringToSignBytes>
<RequestId>11A7BD415D04AAFE7E</RequestId>
<HostId>3zFeVQCbO+LraKZ7sR1j7rgMR9KdyOEqKFGX/5QCWXMhXLBubzre7Lb1eun/zATJU/xz69mpg+o=</HostId>
</Error>

我一直在寻找其他帖子,但尚未找到解决方案。

我发现的一些建议是:

  • 不要在 SECRET ACCESS KEY 中包含“/”。 (我的密钥不包含斜线)
  • 不正确的凭据(我已经用 aws cli 测试了密钥,它有效)
  • 更新存储桶权限和策略。 (我已经更新了政策的所有访问权限)

我的桶设置如下:

存储桶策略

{
    "Version": "2012-10-17",
    "Id": "Policy1594951813323",
    "Statement": [
        {
            "Sid": "Stmt15949510950",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::<AccountNumber>:root"
            },
            "Action": "s3:*",
            "Resource": "arn:aws:s3:::<bucketname>/*"
        }
    ]
}

CORS配置

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>POST</AllowedMethod>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedMethod>PUT</AllowedMethod>
    <AllowedMethod>DELETE</AllowedMethod>
    <AllowedMethod>HEAD</AllowedMethod>
    <MaxAgeSeconds>3000</MaxAgeSeconds>
    <AllowedHeader>*</AllowedHeader>
    <AllowedHeader>Authorization</AllowedHeader>
</CORSRule>
</CORSConfiguration>

更新的解决方案

Use PUT Instead of POST for the pre-sign url to upload file to S3

原文由 Jackal 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 688
1 个回答

在使用 Lambda functionsAPI Gateway 时,有几件事需要考虑,

  1. 使用预签名 URL 时,请检查您的请求方法是 PUT 还是 POST 。它应该是 PUT
  2. 在 AWS 中检查您的 lambda function 并确保 ContentType 与您的上传匹配。
  3. 确保您在请求中设置的 headers params 与 lambda 中的 — 匹配。功能。

原文由 Lenzman 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题