我目前正在尝试设置静态 Web 应用程序,以使用 Vanilla Javascript 获取/发布数据到我的 Azure 表。我正在尝试使用 POSTMAN 和简单的 GET 请求来测试 REST API。然而,我犯了一个错误:
服务器无法验证请求。确保授权标头的值格式正确,包括签名。
这是我的代码:
var date = new Date();
var utcDate = date.toUTCString();
CanonicalizedResource = "" + "/" + "accountname/" + 'Tables';
ContentMD5 = "";
ContentType = ""; //Should this be empty? I've tried application/json as well as text/plain
StringToSign = "GET" + "\n" +
ContentMD5 + "\n" +
ContentType + "\n" +
utcDate + "\n" +
CanonicalizedResource;
var hmac = computeHMACSHA256(StringToSign, 'key from Azure Table');
console.log(StringToSign);
console.log(utcDate);
console.log(hmac);
function computeHMACSHA256(stringToSign, accountKey) {
const key = Buffer.from(accountKey, "base64");
return crypto.createHmac("sha256", key).update(stringToSign, "utf8").digest("base64");
} //this function is taken from the Javascript client service so that I could test.
在 Postman 中,我的 GET 请求中有 4 个标头。
授权:SharedKey 账户名:签名
日期:GMT 日期
x-ms-版本:2019-02-02
数据服务版本:3.0;NetFx
我已通读 Azure 文档来创建签名,但仍然没有成功。我已使用 Azure Javascript 客户端服务来测试连接,并且它有效。出于管理目的,我更愿意使用 REST HTTP 请求与表进行通信。
不幸的是,我无法通过使用此特定设置进行搜索来找到任何内容。我已经使用 SharedKeyLite(通过客户端服务)验证了它的工作原理。我认为我的 StringToSign 有问题,但仍不确定。
希望有人能看到这里出了什么问题。
您似乎正在尝试为 Azure 表存储请求手动生成共享密钥 Lite 身份验证。该问题可能与您构建 StringToSign 和 Authorization 标头的方式有关。
这是代码的替代版本,并附有一些解释:
const crypto = require('crypto');
// Function to compute HMAC-SHA256
function computeHMACSHA256(stringToSign, accountKey) {
const key = Buffer.from(accountKey, "base64");
return crypto.createHmac("sha256", key).update(stringToSign, "utf8").digest("base64");
}
// Construct the request headers
const date = new Date().toUTCString();
const canonicalizedResource = "/" + "accountname/" + 'Tables';
const contentMD5 = "";
const contentType = ""; // Use application/json if you're sending JSON data
const stringToSign = `GET\n${contentMD5}\n${contentType}\n${date}\n${canonicalizedResource}`;
// Replace 'key from Azure Table' with your actual account key
const signature = computeHMACSHA256(stringToSign, 'key from Azure Table');
// Construct the Authorization header
const authorizationHeader = `SharedKey accountname:${signature}`;
console.log("StringToSign:", stringToSign);
console.log("Date:", date);
console.log("Authorization Header:", authorizationHeader);
注意: 确保将“Azure 表中的密钥”替换为您实际的 Azure 表存储帐户密钥。
此外,在构造 StringToSign 时,请确保 CanonicalizedResource 包含您正在与之交互的特定表名称。
例如,如果您的表名为 'MyTable',则 CanonicalizedResource 应为 "/accountname/Tables/MyTable"。