如何为Blob /容器生成Azure共享访问签名?

时间:2019-05-24 09:58:57

标签: javascript azure azure-storage azure-storage-emulator

鉴于我的环境限制,并且SAS似乎是一个简单的令牌,我想手动生成它。

我尝试遵循Microsoft documentation的SAS生成方式,但始终收到错误消息:

curl.exe -X PUT -T .\arckep2.jpg -H "Content-Type: image/jpeg"  -H "x-ms-date: $now" -H "x-ms-blo
b-type: BlockBlob" "http://127.0.0.1:10000/devstoreaccount1/profile-images/arckep3.jpg?sv=2018-03-28&sr=c&sig=2%2FKJVDhs2O5%2F5nAGpGzxRhnN4PE4AqPHOe3fFe7qC7o%3D&st=2019
-05-23T00%3A00%3A00Z&se=2019-05-25T00%3A00%3A00Z&sp=rwdl"

返回:

<?xml version="1.0" encoding="utf-8"?><Error><Code>AuthenticationFailed</Code><Message>Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.
RequestId:d1313189-cde5-463d-8476-1aab15a9f03d
Time:2019-05-24T09:20:16.1975584Z</Message><AuthenticationErrorDetail>Signature did not match. String to sign used was rwdl
2019-05-23T00:00:00Z
2019-05-25T00:00:00Z
/blob/devstoreaccount1/profile-images



2018-03-28




</AuthenticationErrorDetail></Error>

这是怎么了?

我尝试将azure-sdk-for-js复制到一个代码笔中:https://codepen.io/nagyv/pen/MdVpgX

const secret = "Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw=="  // Secret for every Azure storage emulator

function getParts() {
  return [
    "rwdl",
    "2019-05-23T00:00:00Z",
    "2019-05-25T00:00:00Z",
    "/blob/devstoreaccount1/profile-images",
    "",
    "",
    "",
    "2018-03-28",
    "",
    "",
    "",
    "",
    ""
  ].join("\n")
}
const parts = getParts()

function sign(message) {
  const crypted = CryptoJS.HmacSHA256(message, secret);
  return CryptoJS.enc.Base64.stringify(crypted)
}

const content = document.getElementById('content')
content.innerHTML = encodeURIComponent(sign(parts))

上下文

我想使用基于JavaScript的在线无服务器后端(GameSparks)为基于浏览器的应用程序生成SAS。不幸的是,考虑到后端,我无法使用azure节点SDK生成SAS。由于SAS似乎是一个简单的令牌,我想“手动”生成它。

1 个答案:

答案 0 :(得分:0)

经过一些处理后,我意识到问题出在Azure解决方案的情况下,秘密被base64解码了。

这显示了如何生成相同的摘要:https://stackoverflow.com/a/56295850/245493

此更改为

function sign(message) {
  const crypted = CryptoJS.HmacSHA256(message, CryptoJS.enc.Base64.parse(secret))
  return CryptoJS.enc.Base64.stringify(crypted)
}

解决了我的问题。