Search code examples
javascriptazureazure-storageazure-storage-emulator

how to generate an azure shared access signature for blob/container?


Given my environments limitations and that the SAS seems to be a simple token, I would like to generate it "by hand".

I tried to follow Microsoft's documentation how SAS is generated, but I always receive an error:

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"

returns:

<?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>

What's wrong with this?

I tried to replicate azure-sdk-for-js's in a codepen: 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))

Context

I would like to use an online, javascript based serverless backend (GameSparks) to generate a SAS for my browser-based app. Unfortunately, given the backend, I can't use the azure node SDKs to generate the SAS. As the SAS seems to be a simple token, I would like to generate it "by hand".


Solution

  • After some crunching, I realized that the problem is with the secret being base64 decoded in case of Azure's solution.

    This shows how to get the same digest generated: https://stackoverflow.com/a/56295850/245493

    This changing to

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

    solves my question.