javaazureazure-blob-storagesas-token

How to generate SAS token for Azure from Java with the same structure as the one generated from Azure Portal?


I am trying to upload a file to an Azure container from a basic Spring Boot application, and I was successful so far. However, when I try to read or write the tags on the Azure blob, I keep getting the following error, which makes me think I am missing some authorization on the SAS token.

com.azure.storage.blob.models.BlobStorageException: If you are using a StorageSharedKeyCredential, and the server returned an error message that says 'Signature did not match', you can compare the string to sign with the one generated by the SDK. To log the string to sign, pass in the context key value pair 'Azure-Storage-Log-String-To-Sign': true to the appropriate method call.
If you are using a SAS token, and the server returned an error message that says 'Signature did not match', you can compare the string to sign with the one generated by the SDK. To log the string to sign, pass in the context key value pair 'Azure-Storage-Log-String-To-Sign': true to the appropriate generateSas method call.
Please remember to disable 'Azure-Storage-Log-String-To-Sign' before going to production as this string can potentially contain PII.
Status code 403, "<?xml version="1.0" encoding="utf-8"?>
<Error><Code>AuthorizationPermissionMismatch</Code><Message>This request is not authorized to perform this operation using this permission.

The SAS token is generated as follows:

OffsetDateTime startTime = OffsetDateTime.now().minusMinutes(1);
OffsetDateTime expiryTime = startTime.plusHours(10);
UserDelegationKey userDelegationKey = blobServiceClient.getUserDelegationKey(startTime, expiryTime);

BlobSasPermission sasPermission = new BlobSasPermission()
    .setAddPermission(true)
    .setCreatePermission(true)
    .setDeletePermission(true)
    .setDeleteVersionPermission(true)
    .setExecutePermission(true)
    .setListPermission(true)
    .setMovePermission(true)
    .setPermanentDeletePermission(true)
    .setReadPermission(true)
    .setTagsPermission(true)
    .setWritePermission(true);

BlobServiceSasSignatureValues sasSignatureValues = new BlobServiceSasSignatureValues(expiryTime, sasPermission)
    .setStartTime(startTime);

BlobClient blobClient = blobContainerClient.getBlobClient("someBlob");
String sasToken = blobClient.generateUserDelegationSas(sasSignatureValues, userDelegationKey);

where blobServiceClient and blobContainerClient are two fields automatically injected in my service class (the application.yml of my application contains spring.cloud.azure.storage.blob.container-name and spring.cloud.azure.storage.blob.endpoint).

I don't have any issue when I generate a token via the Azure Portal. I can see that it has a slightly different structure, containing a srt section (corresponding to the Allowed resource types on the Portal) which I can't seem to generate from Java:

How can I generate a "good" SAS token that allows me to read/write tags on an Azure blob in Java?


Solution

  • How can I generate a "good" SAS token that allows me to read/write tags on an Azure blob in Java?.

    You can generate SAS token as same as portal, with MS-Document using Azure Java SDK.

    Code:

        private final String accountName = "venkat326123";
        private final String accountKey = "Txxxx=";
        private final StorageSharedKeyCredential credential;
        private final BlobServiceClient blobServiceClient;
        private final BlobClient blobClient;
        private final BlobClient sasBlobClient;
    
        public App() {
            credential = new StorageSharedKeyCredential(accountName, accountKey);
    
            blobServiceClient = new BlobServiceClientBuilder()
                .endpoint(String.format("https://%s.blob.core.windows.net/", accountName))
                .credential(credential)
                .buildClient();
    
            blobClient = blobServiceClient
                .getBlobContainerClient("test")
                .getBlobClient("example.csv");
    
            OffsetDateTime expiryTime = OffsetDateTime.now().plusDays(1);
            BlobSasPermission sasPermission = new BlobSasPermission()
                .setReadPermission(true)
                .setWritePermission(true)
                .setTagsPermission(true); 
    
            BlobServiceSasSignatureValues sasSignatureValues = new BlobServiceSasSignatureValues(expiryTime, sasPermission)
                .setStartTime(OffsetDateTime.now().minusMinutes(5));
    
            String sasToken = blobClient.generateSas(sasSignatureValues);
            System.out.println("Generated SAS Token: " + sasToken);
    
            sasBlobClient = new BlobClientBuilder()
                .endpoint(blobClient.getBlobUrl() + "?" + sasToken)
                .buildClient();
        }
    
        public void writeBlobTags() {
            Map<String, String> tags = new HashMap<>();
            tags.put("project", "quickstart");
            tags.put("env", "test");
            sasBlobClient.setTags(tags);
            System.out.println("Tags added to the blob.");
        }
    
        public void readBlobTags() {
            Map<String, String> tags = sasBlobClient.getTags();
            System.out.println("Blob tags: " + tags);
        }
    
        public static void main(String[] args) {
            App app = new App();  
            app.writeBlobTags();  // Write tags to the blob
            app.readBlobTags();   // Read tags from the blob
        }
    

    Output:

    Generated SAS Token: sv=2023-11-03&st=2024-09-02T03%3A57%3A22Z&se=2024-09-03T04%3A02%3A22Z&sr=b&sp=rwt&sig=cwrK%2F2yuuHyxxxxxx
    Tags added to the blob.
    Blob tags: {project=quickstart, env=test}
    

    enter image description here

    Portal:

    enter image description here