问题
I want to generate a SAS url that i can share with user to connect to storage account and upload a file to any location.
How can i generate the SAS url using java api.
i found one documentation but looks like all api are depreciated https://azuresdkdocs.blob.core.windows.net/$web/java/azure-storage-blob/12.0.0/com/azure/storage/blob/sas/BlobServiceSasSignatureValues.html
Env:
Java Version: 8.0
BLOB STORAGE JAVA SDK: group: 'com.azure', name: 'azure-storage-blob', version: '12.8.0'
回答1:
There's a REST API that you can call. See at https://docs.microsoft.com/en-us/rest/api/storageservices/create-service-sas.
回答2:
Following code worked for me.
BlobContainerSasPermission blobContainerSasPermission = new BlobContainerSasPermission()
.setReadPermission(true)
.setWritePermission(true)
.setListPermission(true);
BlobServiceSasSignatureValues builder = new BlobServiceSasSignatureValues(OffsetDateTime.now().plusDays(1), blobContainerSasPermission)
.setProtocol(SasProtocol.HTTPS_ONLY);
BlobClient client = new BlobClientBuilder()
.connectionString("connection string")
.blobName("")
.buildClient();
String blobContainerName = "test";
return String.format("https://%s.blob.core.windows.net/%s?%s",client.getAccountName(), blobContainerName, client.generateSas(builder));
回答3:
After my tests, you can also generate SAS in the following form:
StorageSharedKeyCredential credential = new StorageSharedKeyCredential("<accountName>", "<accountKey>");
String sas = new BlobServiceSasSignatureValues()
.setExpiryTime(OffsetDateTime.now().plusHours(1))
.setPermissions(new BlobSasPermission().setReadPermission(true))
.setContainerName("<containerName>")
.setBlobName("blobName")
.generateSasQueryParameters(credential)
.encode();
回答4:
You can use azure storage SDK for maven as follows:
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure-storage</artifactId>
<version>8.3.0</version>
</dependency>
Then follow the below code to generate SAS token which you can append to your storage URL.
CloudStorageAccount account = CloudStorageAccount.parse(blobConnectionString);
// Create a blob service client
CloudBlobClient blobClient = account.createCloudBlobClient();
CloudBlobContainer container = blobClient.getContainerReference(containerName);
Date expirationTime = Date.from(LocalDateTime.now().plusDays(7).atZone(ZoneOffset.UTC).toInstant());
SharedAccessBlobPolicy sharedAccessPolicy=new SharedAccessBlobPolicy();
sharedAccessPolicy.setPermissions(EnumSet.of(SharedAccessBlobPermissions.READ,
SharedAccessBlobPermissions.WRITE,SharedAccessBlobPermissions.ADD));
sharedAccessPolicy.setSharedAccessStartTime(new Date());
sharedAccessPolicy.setSharedAccessExpiryTime(expirationTime);
String sasToken = container.generateSharedAccessSignature(sharedAccessPolicy, null);
来源:https://stackoverflow.com/questions/64781212/how-to-generate-azure-blob-storage-sas-url-using-java