Azure Table 通过 javascript 存储验证 REST 调用

Azure Table Storage Authenticate REST call through javascript

我正在尝试使用 javascript 对我的 Azure Table 进行 REST 调用,但我发现很难对调用进行身份验证。

我正在使用 javascript 的那个片段(我知道日期必须最多 15 分钟,而且我不打算使用 javascript 中的实际密钥!)

$(document).ready(function(){
    $("button").click(function(){
        var dateTimeInUtc = 'Fri, 12 Feb 2016 12:14:00 GMT';
        var version = '2015-04-05';
        var key = 'JEwMjqFD1ng8vIaECmRw8eQysiIvH08nF/jPKPYaNGumgxtKIjltX8bte5sKN6SNyw09s=='; // not an actuall key
        var stringToSign = 'GET\n\n\nFri, 12 Feb 2016 12:14:00 GMT\n/myaccount/mytable(PartitionKey=\'first_partition\', RowKey=\'1235\')';
        var signature = CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA256(CryptoJS.enc.Utf8.parse(stringToSign), CryptoJS.enc.Base64.parse(key)));
        $.ajax({
            url:'https://myaccount.table.core.windows.net/mytable(PartitionKey=\'first_partition\', RowKey=\'1235\')',
            type: 'GET',
            success: function (data) {
                console.log('well done');
            },
            beforeSend: function (xhr) {
                xhr.setRequestHeader('Authorization', "SharedKey " + "myaccount" + ":" + signature);
                xhr.setRequestHeader('x-ms-date', dateTimeInUtc);
                xhr.setRequestHeader('x-ms-version', version);
            },
            error: function (rcvData) {
                console.log(rcvData);
            }
        });
    });
});

我得到了什么

403 (Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.)

你有没有发现明显的错误?我是否遗漏了签名中的某些内容?

基于documentation for creating authorization header,创建要签名的字符串:

  1. Beginning with an empty string (""), append a forward slash (/), followed by the name of the account that owns the resource being accessed.
  2. Append the resource's encoded URI path, without any query parameters.
  3. Append a new-line character (\n) after the resource name.

但是在您的代码中,您没有包含 (PartitionKey=\'first_partition\', RowKey=\'1235\') 应该包含的内容。

你能试试下面的方法吗:

var stringToSign = 'GET\n\n\nFri, 12 Feb 2016 12:14:00 GMT\n/htirawdata/htirawdata(PartitionKey=\'first_partition\', RowKey=\'1235\')';

您构建的待签名字符串必须与通过网络传输的 URL 完全一致,包括 URL 中不允许的百分比编码字符。在这种情况下,URL 中的 space 字符将通过网络进行百分比编码,因此它必须在待签名字符串中进行百分比编码。

来自MSDN page

Any portion of the CanonicalizedResource string that is derived from the resource's URI should be encoded exactly as it is in the URI.