Azure Blob:无法通过 java SDK 生成下载 link

Azure Blob: failed to generate download link by java SDK

我正在使用 azure-storage-blob java SDK 将文件上传到 Azure blob 并生成 SAS 密钥以下载文件。下面是我的代码。

String accountName = "accountName";
String accountKey = "accountKey";
String formatUrl = "https://%s.blob.core.windows.net";    
String endpoint = String.format(Locale.ROOT, formatUrl, accountName);
StorageSharedKeyCredential credential = new StorageSharedKeyCredential(accountName, accountKey);
BlobServiceClient blobServiceClient = new BlobServiceClientBuilder()
            .endpoint(endpoint)
            .credential(credential)
            .buildClient();
BlobClient blobClient = blobServiceClient.getBlobContainerClient(containerName).getBlobClient(blobName);
OffsetDateTime expiryTime = OffsetDateTime.now().plusDays(1);
BlobSasPermission permission = new BlobSasPermission().setReadPermission(true);
BlobServiceSasSignatureValues values = new BlobServiceSasSignatureValues(expiryTime, permission)
            .setStartTime(OffsetDateTime.now());
String sasToken = blobClient.generateSas(values);
String fileUrl = blobClient.getBlobUrl();
String downloadLink = fileUrl + "?" + sasToken;

下载文件没问题。但是如果你每秒生成一次 link,第一个和第二个 link 工作正常,也许点击第三个 link 会出错。将显示来自 Azure

的错误页面 AuthenticationFailed 服务器无法验证请求。确保 Authorization header 的值格式正确,包括签名。 RequestId:******时间:2021-08-13T09:28:36.7981577Z 签名在指定的时间范围内无效:开始 [2021 年 8 月 13 日,星期五 09:28:37 GMT] - 到期 [2021 年 8 月 14 日,星期六 09:28:37 GMT] - 当前 [2021 年 8 月 13 日,星期五 09:28:36 格林威治标准时间]

我该怎么办?

感谢 Gaurav 在评论中提供您的建议,我正在转换为帮助其他社区成员的答案。

要使 SAS 令牌立即生效,您可以安全地省略 SAS 开始时间,而只使用 SAS 到期时间。 SAS 开始时间是可选的

参考:BlobServiceSasSignatureValues(OffsetDateTime expiryTime, BlobContainerSasPermission permissions)

如果您使用的是开始时间,请参考下面的文档,开始时间应该传入方法本身,而不是用 .setStartTime(OffsetDateTime.now());

调用

BlobServiceSasSignatureValues Constructor | Microsoft Docs