gpt4 book ai didi

c# - 如何生成 SAS token 以安全连接到 Azure IOT 中心

转载 作者:行者123 更新时间:2023-12-03 04:18:51 25 4
gpt4 key购买 nike

我需要以编程方式生成 SAS连接到 Azure 所需的 token 物联网中心。为此,我关注这个page .

在下面的 C# 代码中:

private static string createToken(string resourceUri, string keyName, string key)
{
TimeSpan sinceEpoch = DateTime.UtcNow - new DateTime(1970, 1, 1);
var week = 60 * 60 * 24 * 7;
var expiry = Convert.ToString((int)sinceEpoch.TotalSeconds + week);
string stringToSign = HttpUtility.UrlEncode(resourceUri) + "\n" + expiry;
HMACSHA256 hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key));
var signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));
var sasToken = String.Format(CultureInfo.InvariantCulture, "SharedAccessSignature sr={0}&sig={1}&se={2}&skn={3}", HttpUtility.UrlEncode(resourceUri), HttpUtility.UrlEncode(signature), expiry, keyName);
return sasToken;
}

我们需要输入resourceUri我相信是 <somename>.azure-devices.net ,keyname 是策略名称,key 可以用作主键或辅助键。

使用上述参数并生成 SAS token 后,我仍然面临授权问题,并且我的设备在设备资源管理器中显示为已断开连接。谁能告诉我我在这里用错了什么。

谢谢

最佳答案

尝试以下更改:

    private static string createToken(string resourceUri, string key, string keyName = null)
{
TimeSpan sinceEpoch = DateTime.UtcNow - new DateTime(1970, 1, 1);
var week = 60 * 60 * 24 * 7;
var expiry = Convert.ToString((int)sinceEpoch.TotalSeconds + week);
string stringToSign = HttpUtility.UrlEncode(resourceUri) + "\n" + expiry;
HMACSHA256 hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key));
var signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));

var sasToken = keyName == null ?
String.Format(CultureInfo.InvariantCulture, "SharedAccessSignature sr={0}&sig={1}&se={2}", HttpUtility.UrlEncode(resourceUri), HttpUtility.UrlEncode(signature), expiry) :
String.Format(CultureInfo.InvariantCulture, "SharedAccessSignature sr={0}&sig={1}&se={2}&skn={3}", HttpUtility.UrlEncode(resourceUri), HttpUtility.UrlEncode(signature), expiry, keyName);

return sasToken;

}

用法:

var deviceSasToken = MyHelper.createToken("{somename}.azure-devices.net/devices/myDeviceId", devicePrimaryKey);

关于c# - 如何生成 SAS token 以安全连接到 Azure IOT 中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50814994/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com