javascript - 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>
请告知如何调试或提示此功能可能有什么问题。
解决方案
稍微研究一下,似乎AWS4-HMAC-SHA256
可以定义一个特定的哈希算法。看着这个(很棒的)要点,作者说出了完整的算法名称。
您可以尝试将您的电话 ( { name: 'HMAC', hash: 'SHA-256' }
)替换为{ name: 'HMAC', hash: 'AWS4-HMAC-SHA256' }
-
另一个想法是从算法名称中删除破折号 ( )。从SHA-256
to 去SHA256
看看是否有差异。
推荐阅读
- java - 将 Optaplanner 集成到 Java Web 应用程序中
- bash - 如何使用 bash 脚本命令替换 csv 文件中的列标题和值?
- python-3.x - 在 aws lambda 中使用 python subprocess.popen
- docker - 当我已经有服务器配置时,PhpStorm 一直要求配置“来自 Xdebug 的传入连接”
- javascript - 如何使用 react-native-html-to-pdf 在 React native Expo 中创建 PDF?
- reactjs - 类的实例在哪里创建
- python-3.x - 用于 Spotify 本地控制的 API
- google-sheets-formula - 根据邻居日期对所有数字求和
- python - 在图像上投影 3x4 矩阵点
- javascript - 如何使用通过函数创建的数组?