0
votes

I'm using azure-storage-blob java SDK to upload file to Azure blob and generating SAS key to download file. Here below are my code.

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;

It's work fine to download a file. But if you generate link once per second, the first and second link works fine, maybe there is an error snice clicking third link. There will display an error page from Azure

AuthenticationFailed Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature. RequestId:******Time:2021-08-13T09:28:36.7981577Z Signature not valid in the specified time frame: Start [Fri, 13 Aug 2021 09:28:37 GMT] - Expiry [Sat, 14 Aug 2021 09:28:37 GMT] - Current [Fri, 13 Aug 2021 09:28:36 GMT]

What's should I do?

1
Considering you want your SAS token to be effective immediately, you can safely omit the SAS start time and just use the SAS expiry time. SAS start time is optional.Gaurav Mantri
It's works for me! Thank you very much! @GauravMantriRiven

1 Answers

2
votes

Thank You Gaurav for providing your suggestion in the comment and I am converting as an answer to help other community member.

For SAS token to be effective immediately, you can safely omit the SAS start time and just use the SAS expiry time. SAS start time is optional

Reference : BlobServiceSasSignatureValues(OffsetDateTime expiryTime, BlobContainerSasPermission permissions)

If you are using start time refer the below document start time should pass in method itself not to call with .setStartTime(OffsetDateTime.now());

BlobServiceSasSignatureValues Constructor | Microsoft Docs