Search code examples
azureazure-storageazure-blob-storageazure-java-sdk

Generate Signed URL for Azure Blob Storage using Java SDK


I am trying to create signed URLs for a file in Azure Blob using Java SDK. Here is the snippet that is used -

String container = "test";
String path = "hello/world.json";
long expiry = 2000;
SharedKeyCredentials creds = new SharedKeyCredentials(accountName, accountKey);

BlobSASPermission blobSASPermission = new BlobSASPermission().withRead(true).withCreate(true).withWrite(true);

AccountSASSignatureValues signatureValues = new AccountSASSignatureValues()
        .withResourceTypes(new AccountSASResourceType().withService(true).withContainer(true).withObject(true).toString())
        .withServices(new AccountSASService().withBlob(true).toString())
        .withPermissions(blobSASPermission.toString())
        .withProtocol(SASProtocol.HTTPS_ONLY)
        .withStartTime(OffsetDateTime.now())
        .withExpiryTime(OffsetDateTime.now().plusSeconds(expiry));


URL blobURL = new BlobURLParts()
        .withScheme("https://")
        .withHost(accountName + ".blob.core.windows.net")
        .withContainerName(container)
        .withBlobName(path)
        .withSasQueryParameters(signatureValues.generateSASQueryParameters(creds))
        .toURL();

When I send out a GET/PUT/POST curl request on the blobURL I get the following error

<?xml version="1.0" encoding="utf-8"?><Error><Code>AuthenticationFailed</Code><Message>Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.
RequestId:c8192b20-c01e-0056-23ca-5e06e8000000
Time:2019-08-30T00:30:03.2903571Z</Message><AuthenticationErrorDetail>Signature did not match. String to sign used was playmentdiag
rcw
b
sco
2019-08-30T00:27:42Z
2019-08-30T01:01:02Z

https
2018-03-28
</AuthenticationErrorDetail></Error>

What am I doing wrong? I tried to upload files with the same credentials and it worked perfectly fine. Java SDK- com.microsoft.azure:azure-storage-blob:10.1.0


Solution

  • Seems there is something conflicts with blob SAS permission create and write, disable either of them , your code works well on my side with the similar env as you:

    BlobSASPermission blobSASPermission = new BlobSASPermission().withRead(true).withCreate(false).withWrite(true);
    

    or

    BlobSASPermission blobSASPermission = new BlobSASPermission().withRead(true).withCreate(true).withWrite(false);
    

    Btw, this is the only doc I can find: https://learn.microsoft.com/en-us/rest/api/storageservices/create-account-sas#constructing-the-account-sas-uri , as you can see under "SignedPermission" section indicated that the create permission can not overwrite existing blobs or files , but write permission is used for writing to existing objs , I think this is the conflict here .