3

I need to get sharable link, where world can see file from azure blob with expiry using spring boot. Thanks in Advance!

1 Answers1

2

Try code below to get a SAS token with read permission for a blob :

import com.azure.storage.blob.sas.BlobServiceSasSignatureValues;
import com.azure.storage.blob.sas.BlobSasPermission;
import com.azure.storage.blob.BlobClient;
import com.azure.storage.blob.BlobServiceClient;
import com.azure.storage.blob.BlobServiceClientBuilder;
import java.time.OffsetDateTime;

public class App {
        public static void main(String[] args) {

                String connString = "<storage account connection string>";
                String containerName = "<container name>";
                String blobName = "<blob 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); // after 2 days expire
                BlobServiceSasSignatureValues values = new BlobServiceSasSignatureValues(expiryTime, blobSasPermission)
                                .setStartTime(OffsetDateTime.now());

                System.out.println(blobClient.getBlobUrl() + "?" + blobClient.generateSas(values));

        }
}

maven dependency:

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

Result:

enter image description here

Access this file using this URL:

enter image description here

Stanley Gong
  • 11,522
  • 1
  • 8
  • 16
  • Is it possible to generate a permanent sharable link ? – mothi sampath Apr 23 '21 at 15:06
  • Yes, the easiest way to do this is expanding `expiryTime`, in my demo code, in my code I just added 2 days time to expire, you can add, for instance, 3650 days (10 years). And if my post is helpful for you, could you pls kindly click the checkmark beside my answer to accept it? I would be glad to assist you if you have any more questions. – Stanley Gong Apr 25 '21 at 13:02
  • I am trying to use "TokenCredential" to conenct to storage account but it is requiring a "storageSharedKeyCredential". Can you help me with this? – Numan Karaaslan Sep 01 '21 at 09:40