如何生成 SAS 令牌以安全连接到 Azure IOT 中心

How to generate SAS token for secure connection to Azure IOT hub

我需要以编程方式生成连接到 Azure IoT 中心所需的 SAS 令牌。为此,我正在关注这个 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 令牌后,我仍然面临授权问题,并且我的设备在设备资源管理器中显示为已断开连接。谁能告诉我我这里用错了什么。

谢谢

尝试以下更改:

    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);

如果您输入的密钥是您设备的主密钥,那么在上面的代码片段中:

HMACSHA256 hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key));

必须是:

HMACSHA256 hmac = new HMACSHA256(Convert.FromBase64String(key));

那对我有用。