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

SharedAccessSignature的格式如下:

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 官方文档说明如下:

{signature} :An HMAC-SHA256 signature string of the form: {URL-encoded-resourceURI} + "\n" + expiry. Important: The key is decoded from base64 and used as key to perform the HMAC-SHA256 computation.

再来看Azure Service Bus 的官方文档说明:

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.

网友评论