Azure Table Storage 通过 javascript 对 REST 调用进行身份验证

Azure Table Storage Authenticate REST call through javascript

本文关键字:调用 身份验证 REST Table Storage 通过 javascript Azure      更新时间:2023-09-26

我正在尝试使用javascript对我的Azure表进行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.)

你看出有什么明显的问题吗?我是否错过了签名中的某些内容?

您构造的字符串到签名必须是通过网络传输的确切 URL,包括 URL 中不允许的百分比编码字符。在这种情况下,URL 中的空格字符将通过线路进行百分比编码,因此必须在字符串到签名中对其进行百分比编码。

从 MSDN 页面:

从资源的 URI 派生的 CanonicalizedResource 字符串的任何部分都应完全按照它在 URI 中的编码方式进行编码。

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

  1. 以空字符串 (") 开头,附加一个正斜杠 (/),后跟拥有该资源的帐户的名称 访问。
  2. 追加资源的编码 URI 路径,不带任何查询参数。
  3. 在资源名称后附加换行符 (')。

但是,在您的代码中,您没有包含应该包含(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'')';