首页 > 解决方案 > Aws4 签署 S3 PUT 请求

问题描述

编写将在 Cloudflare worker 上运行的专用 S3 文件上传请求签名函数(我想应该与浏览器中的相同):

let s3PutSign = function(region, keyId, keySecret, contentType, date, bucket, fileName) {
    return crypto.subtle.importKey('raw', new TextEncoder().encode(keySecret), { name: 'HMAC', hash: 'SHA-256' }, true, ['sign'])
        .then(key => {
            let path = `/${bucket}/${fileName}`
            let strToSign = `PUT\n\n${contentType}\n${date}\n${path}`
            return crypto.subtle.sign('HMAC', key, new TextEncoder().encode(strToSign))
                .then(sig => {
                    return {
                        url: `https://s3.${region}.amazonaws.com${path}`,
                        headers: { 
                            'content-type': contentType,
                            'Authorization': `AWS ${keyId}:${btoa(sig)}`,
                            'x-amz-date': new Date(new Date().getTime() + 10000).toISOString().replace(/[:\-]|\.\d{3}/g, '').substr(0, 17)
                        }
                    }
                })
        })
}

使用 PUT 示例编写函数:https ://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html

变量strToSign

PUT

application/pdf
Wed, 27 May 2020 12:26:33 GMT
/mybucket/file.pdf

函数结果:

{
  url: "https://s3.eu-central-1.amazonaws.com/mybucket/file.pdf",
  headers: {
    content-type: "application/pdf",
    Authorization: "AWS AKXAJE7XIIVXQZ4X7FXQ:W29iamVXZCBBcnJheUJ1ZmZlcl0=",
    x-amz-date: "20200527T122643Z"
  }
}

请求总是产生以下响应:

<?xml version="1.0" encoding="UTF-8"?>
<Error>
  <Code>InvalidRequest</Code>
  <Message>The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256.</Message>
  <RequestId>7CECC87D5E855C48</RequestId>
  <HostId>rtGLR0u9Qc29bllgKnJf7xD00iQ0+/BZog5G/wYWjsN8tkXio9Baq7GZvbQTD40EVCQ9FzuCo9c=</HostId>
</Error>

请告知如何调试或提示此功能可能有什么问题。

标签: javascriptamazon-s3cryptography

解决方案


稍微研究一下,似乎AWS4-HMAC-SHA256可以定义一个特定的哈希算法。看着这个(很棒的)要点,作者说出了完整的算法名称。

您可以尝试将您的电话 ( { name: 'HMAC', hash: 'SHA-256' })替换为{ name: 'HMAC', hash: 'AWS4-HMAC-SHA256' }

-另一个想法是从算法名称中删除破折号 ( )。从SHA-256to 去SHA256看看是否有差异。


推荐阅读