首页 > 解决方案 > 如何创建字符串以在 Azure 中为 blob 签名以生成SharedAccessSignature

问题描述

我正在尝试从 string_to_sign 为 Azure bloc 创建 hmac 以生成SharedAccessSignature, 但它给了我一个错误“签名字段格式不正确”。

下面是我的示例字符串

String data = sprintf("%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s",
            ["r",
            "2020-11-17",
            "2020-11-19",
            "/blob/myAccount/test/member-pic/member-993.png",
            "",
            "",
            "",
            "2017-04-17"]);

  //get hmac string
 String data = base64Encode(mac.convert(utf8.encode(data)).bytes);

标签: azureazure-blob-storage

解决方案


我假设您使用 JAVA 作为您的编程语言,并且您想生成一个具有Read权限和 2 天有效时间的 SAS 令牌。如果是这样,您可以使用 Azure Storage SDK 生成它并直接获取 SAS 令牌,请尝试以下代码:

            String connString = "<storage account connection string >";
            String containerName = "<container name>";
            String blobName = "<file name>";

            BlobServiceClient client = new BlobServiceClientBuilder().connectionString(connString).buildClient();
            BlobClient blobClient = client.getBlobContainerClient(containerName).getBlobClient(blobName);

            BlobSasPermission blobSasPermission = new BlobSasPermission().setReadPermission(true); // grant read
                                                                                                   // permission
                                                                                                   // onmy
            OffsetDateTime expiryTime = OffsetDateTime.now().plusDays(2); // 2 days to expire
            BlobServiceSasSignatureValues values = new BlobServiceSasSignatureValues(expiryTime, blobSasPermission)
                            .setStartTime(OffsetDateTime.now());

            System.out.println(blobClient.generateSas(values));

Maven依赖:

    <dependency>
      <groupId>com.azure</groupId>
      <artifactId>azure-storage-blob</artifactId>
      <version>12.9.0</version>
    </dependency>

推荐阅读