我第一次打电话给Azure Storage REST API一直困扰着我。 Postman的回复显示,这是由于Azure身份验证中的错误,但我不知道问题是什么。
以下是发送Azure存储REST API的浏览器脚本:
function azureListContainers() {
var key = "key-copied-from-azure-storage-account";
var strTime = (new Date()).toUTCString();
var strToSign = 'GET\n\n\n\nx-ms-date:' + strTime + '\nx-ms-version:2015-12-11\n/myaccount/?comp=list';
var hash = CryptoJS.HmacSHA256(strToSign, key);
var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);
var auth = "SharedKeyLite myaccount:"+hashInBase64;
console.log(strToSign);
console.log(auth);
console.log(strTime);
$.ajax({
type: "GET",
beforeSend: function (request)
{
request.setRequestHeader("Authorization", auth);
request.setRequestHeader("x-ms-date", strTime);
request.setRequestHeader("x-ms-version", "2015-12-11");
},
url: "https://myaccount.blob.core.windows.net/?comp=list",
processData: false,
success: function(msg) {
console.log(msg);
}
});
}
Chrome Developer Tool刚刚返回No'Access-Control-Allow-Origin'标题,因此我复制了var auth
和var strTime
的内容,使用Postman工具创建了相同的请求:< / p>
[Command]
GET https://myaccount.blob.core.windows.net/?comp=list
[Headers]
Authorization:SharedKeyLite myaccount:Z9/kY/D+osJHHz3is+8yJRqhj09VUlr5n+PlePUa8Lk=
x-ms-date:Tue, 09 Aug 2016 10:30:49 GMT
x-ms-version:2015-12-11
[Response Body]
<?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:9be3d595-0001-0012-4929-f2fde2000000
Time:2016-08-09T10:31:52.6542965Z</Message>
<AuthenticationErrorDetail>The MAC signature found in the HTTP request 'Z9/kY/D+osJHHz3is+8yJRqhj09VUlr5n+PlePUa8Lk=' is not the same as any computed signature. Server used following string to sign: 'GET
x-ms-date:Tue, 09 Aug 2016 10:30:49 GMT
x-ms-version:2015-12-11
/myaccount/?comp=list'.</AuthenticationErrorDetail>
</Error>
在两个字符串差异之后,我相信我的脚本中的var strToSign
与用于签名的字符串Azure相同。但仍然存在身份验证错误。请帮助说明问题所在。
答案 0 :(得分:3)
Chrome Developer Tool刚刚返回No'Access-Control-Allow-Origin'标题
当您使用javascript直接从客户端向Azure存储服务器发送http请求时。这是一个常见的CORS问题。
当您遇到此问题时,您可以enable the CORS for your storage services。简单来说,您可以利用Microsoft Azure Storage Explorer配置存储空间。
AuthenticationFailed
我根据您的代码片段对我的测试项目进行了两次修改,以使其正常工作。
var hash = CryptoJS.HmacSHA256(strToSign, key);
第二个参数应该是来自帐户密钥的base64解码,请参阅Azure Storage SDK for node.js SharedKey
方案并使用SharedKey
令牌进行身份验证,以使您的方案正常运行。这是我的测试代码段,FYI。,
var key = "key-copied-from-azure-storage-account";
var strTime = (new Date()).toUTCString();
var strToSign = 'GET\n\n\n\n\n\n\n\n\n\n\n\nx-ms-date:' + strTime + '\nx-ms-version:2015-12-11\n/<accountname>/\ncomp:list';
var secret = CryptoJS.enc.Base64.parse(key);
var hash = CryptoJS.HmacSHA256(strToSign, secret);
var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);
var auth = "SharedKey <accountname>:"+hashInBase64;
此外,出于安全原因,请在后端Web服务器中实施Azure存储服务。在客户端使用纯JavaScript时,会将您的帐户名和帐户密钥公开,这会增加您的数据和信息的风险。