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

How to create/delete share access policy in azure blob storage using java?


How i can create or delete share access policy using java api.

Unable to get any official documentation for creating access policy using java SDK.

below is the azure blob dependency i am using in my procject

Gradle dependency: compile group: 'com.azure', name: 'azure-storage-blob', version: '12.8.0'

i found some example but looks like it won't belong to the azure-storage-blob dependency that i am using. https://www.programcreek.com/java-api-examples/?api=com.microsoft.azure.storage.blob.SharedAccessBlobPolicy

is there any api in JAVA SDK for creating / deleting shared access policy for blob storage

enter image description here


Solution

  • Try this:

    import java.time.OffsetDateTime;
    import java.util.ArrayList;
    import com.azure.storage.blob.BlobContainerClient;
    import com.azure.storage.blob.BlobContainerClientBuilder;
    import com.azure.storage.blob.models.BlobAccessPolicy;
    import com.azure.storage.blob.models.BlobSignedIdentifier;
    import com.azure.storage.blob.models.PublicAccessType;
    
    public class App {
            public static void main(String[] args) {
                    String connstr = "<storage account conn str>";
                    String containerName = "<container name>";
    
                    BlobContainerClient blobContainerClient = new BlobContainerClientBuilder().connectionString(connstr)
                                    .containerName(containerName).buildClient();
    
                    BlobSignedIdentifier identifier = new BlobSignedIdentifier().setId("test policy")
                                    .setAccessPolicy(new BlobAccessPolicy().setStartsOn(OffsetDateTime.now())
                                                    .setExpiresOn(OffsetDateTime.now().plusDays(7))
                                                    .setPermissions("cd")); //permission for create and delete
    
                    ArrayList<BlobSignedIdentifier> identifiers = new ArrayList<BlobSignedIdentifier>();
                    identifiers.add(identifier);
                    blobContainerClient.setAccessPolicy(PublicAccessType.CONTAINER, identifiers);
            }       
    }
    

    Result:

    enter image description here