如何生成SAS令牌以实现与Azure IOT集线器的安全连接

时间:2018-06-12 10:30:57

标签: c# azure azure-iot-hub

我需要以编程方式生成与SAS IoT集线器连接所需的Azure令牌。为此我遵循这个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是policyname,key可以用作主键或辅助键。

使用上述参数并生成SAS令牌后,我仍然面临授权问题,我的设备在设备资源管理器中显示为已断开连接。任何人都可以告诉我这里使用的错误。

由于

2 个答案:

答案 0 :(得分:0)

尝试以下更改:

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

答案 1 :(得分:0)

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

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

必须是:

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

那么它对我有用。