2
votes

Is there a way to connect to a storage account or container only using a SAS token and the endpoint for that storage account? I’ve already done the demo/sample and it is using the connection string (which works) but I don’t see how to connect to my storage using only the SAS? Is there any example how to do this in java?

1
Here is the code sample for C#, Java should be something similar: docs.microsoft.com/en-us/azure/storage/common/…Zhaoxing Lu
The follwoing documentation might helps in your scenario: github.com/Azure/azure-storage-java/blob/master/…Vikranth S
@Jim Hi,any progress now? Does my answer helps you?Jay Gong

1 Answers

2
votes

I generate SAS Token for my specific blob on the portal then download it successfully via the token.

enter image description here

sample code:

import com.microsoft.azure.storage.blob.CloudBlockBlob;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;

public class DownloadBlobSAS {

    public static final String blobSasToken = "***";

    public static void main(String[] args) {
        try {
            CloudBlockBlob sasBlob = new CloudBlockBlob(new URI(blobSasToken));

            InputStream input =  sasBlob.openInputStream();
            InputStreamReader inr = new InputStreamReader(input, "UTF-8");
            String utf8str = org.apache.commons.io.IOUtils.toString(inr);
            System.out.println(utf8str);

            System.out.println("print done");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Output Result:

enter image description here

If you want to generate SAS token, you need to provide connection string first to access container or blob.

Then you could use generateSharedAccessSignature() method to create SAS token.You could refer to the sample code:

SharedAccessBlobPolicy sp = createSharedAccessPolicy(
                EnumSet.of(SharedAccessBlobPermissions.READ, SharedAccessBlobPermissions.LIST), 300);
        BlobContainerPermissions perms = new BlobContainerPermissions();

        perms.getSharedAccessPolicies().put("readperm", sp);
        this.container.uploadPermissions(perms);
        Thread.sleep(30000);

        CloudBlockBlob sasBlob = new CloudBlockBlob(new URI(this.blob.getUri().toString() + "?"
                + this.blob.generateSharedAccessSignature(null, "readperm")));

Hope it helps you.