新网Logo
首页>主机-资讯>

告诉你如何为Azure Service Bus和Azure IoT Hub生成SharedAccessSignature

登录 注册

告诉你如何为Azure Service Bus和Azure IoT Hub生成SharedAccessSignature

  • 来源:网络
  • 更新日期:2020-06-05

摘要: 很多服务在做验证的时候都会用到SharedAccessSignature,例如Azure Service Bus, Azure IoT Hub等。今天趟了回大坑,这里分享出来,希望对你有所帮助。 SharedAccessSig

很多服务在做验证的时候都会用到SharedAccessSignature,例如Azure Service Bus, Azure IoT Hub等。今天趟了回大坑,这里分享出来,希望对你有所帮助。

SharedAccessSignature的格式如下:

view sourceprint?
1.SharedAccessSignature sig={signature-string}&se={expiry}&skn={policyName}&sr={URL-encoded-resourceURI}
因此,凭直觉针对不同的服务只要正确指定policyname,resourceURI 就可以计算出相应的SAS。但实际上,对于不同的服务,他们对如何利用秘钥生成signature会存在细微的差别。如果没有注意到这个细微的差别,会让你抓狂两小时。

下面拿Azure Service Bus和Azure IoT Hub进行举例,如果后续我碰到Azure 其他服务有类似的问题。我会更新此文。

首先是Azure IoT Hub, 针对如何生成signature 官方文档说明如下:

view sourceprint?
1.{signature} :An HMAC-SHA256 signature string of the form: {URL-encoded-resourceURI} + \'
2.\' + expiry. <strong>Important:</strong> The key is decoded from base64 and used as key to perform the HMAC-SHA256 computation.
再来看Azure Service Bus 的官方文档说明:

view sourceprint?
1.The signature for the SAS token is computed using the HMAC-SHA256 hash of a string-to-sign with the PrimaryKey property of an authorization rule.
两者的区别在于是否需要对秘钥进行decode。代码分别如下:

view sourceprint?
1.HMACSHA256 hmac = new HMACSHA256(Convert.FromBase64String(key)); // decode the key
2.
3.HMACSHA256 hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key)); // don\'t decode the key
在《Azure IoT Hub 入门 - 权限管理》一文中,我跟大家share了生成SAS的source code 和DLL。该DLL 现支持生成Service Bus 和IoT Hub的SAS,两者通过TargetService来区分(源代码在这里)。调用方法如下:

Service Bus:

view sourceprint?
01.// servicebus
02.string targetURL = \'<a href=sb://sb://<;service bus namespace>.servicebus.chinacloudapi.cn\';
03.string keyName = \'DefaultFullSharedAccessSignature\';
04.string key = <key>;
05.double ttlValue = 1;
06.
07.var sasBuilder = new SharedAccessSignatureBuilder()
08.{
09.TargetService = \'servicebus\',
10.Target = targetURL,
11.KeyName = keyName,
12.Key = key,
13.TimeToLive = TimeSpan.FromDays(ttlValue)
14.};
15.
16.string sas = sasBuilder.ToSignature();
IoT Hub: (TargetService是可选项,默认是生成IoT hub的SAS)

view sourceprint?
01.//iot hub
02.string targetURL = \'<iot hub name>.azure-devices.cn/devices\';
03.string keyName = <policy name>;
04.string key = <key>;
05.
06.var sasBuilder1 = new SharedAccessSignatureBuilder()
07.{
08.Target = targetURL,
09.KeyName = keyName,
10.Key = key,
11.TimeToLive = TimeSpan.FromDays(ttlValue)
12.};
13.
14.string sas1 = sasBuilder1.ToSignature();
15.
16.var sasBuilder2 = new SharedAccessSignatureBuilder()
17.{
18.TargetService=\'iothub\', // optional
19.Target = targetURL,
20.KeyName = keyName,
21.Key = key,
22.TimeToLive = TimeSpan.FromDays(ttlValue)
23.};
24.
25.string sas2 = sasBuilder1.ToSignature();