SALES: 1-800-867-1380

Creating a Shared Access Signature in Java

Updated: April 4, 2014

The following information shows how to create a shared access signature, and how to use a shared access signature, with Java.

For additional information about shared access signatures, including the elements of the shared access signature URL, see Creating a Shared Access Signature.

A shared access signature can be applied to a blob or to a container. The following Java code shows how to create a shared access signature for a container. This code used the 0.4.0 version of the storage libraries.

import com.microsoft.windowsazure.services.blob.client.*;
import com.microsoft.windowsazure.services.core.storage.*;
import java.util.*;
import java.net.URISyntaxException;
import java.security.InvalidKeyException;

public class SAS1 
{

    // Substitute your values for the storage account name and key.
    public static final String storageAccountName = "your_account_name";
    public static final String storageAccountKey = " your_account_key";
    
    // Create the storage connection string based on the account name and key.
    public static final String storageConnectionString = 
            "DefaultEndpointsProtocol=http;" + 
            "AccountName=" + storageAccountName + ";" +
            "AccountKey=" + storageAccountKey;

    public static void main(String[] args) 
    {
        try
        {
            CloudStorageAccount storageAccount;

            // Use the connection string to create the storage account.
            storageAccount = CloudStorageAccount.parse(storageConnectionString);

            // Create the blob client.
            CloudBlobClient blobClient = storageAccount.createCloudBlobClient();

            // Create the container if it does not exist.
            // The container name must be lower case.
            CloudBlobContainer container = blobClient.getContainerReference("mysascontainer");
            container.createIfNotExist();
            
            // Create a shared access policy.
            SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy();
            
            // Create a UTC Gregorian calendar value.
            GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
            
            // Specify the current time as the start time for the shared access signature.
            calendar.setTime(new Date());
            policy.setSharedAccessStartTime(calendar.getTime());
            
            // Use the start time + 1 hour as the end time for the shared access signature. 
            calendar.add(Calendar.HOUR, 1);
            policy.setSharedAccessExpiryTime(calendar.getTime());
            
            // Set READ and WRITE permissions.
            policy.setPermissions(EnumSet.of(SharedAccessBlobPermissions.READ, SharedAccessBlobPermissions.WRITE));
            
            
            // Create the container permissions. 
            BlobContainerPermissions containerPermissions = new BlobContainerPermissions();
            
            // Turn off public access.
            containerPermissions.setPublicAccess(BlobContainerPublicAccessType.OFF);
            
            // Set the policy using the values set above.
            containerPermissions.getSharedAccessPolicies().put("mypolicy", policy);
            container.uploadPermissions(containerPermissions);
            
            // Create a shared access signature for the container.
            String sas = container.generateSharedAccessSignature(policy, null);
            
            System.out.println("The shared access signature was created.");
        }
        catch (URISyntaxException e) 
        {
            System.out.println("URISyntaxException encountered.");
            e.printStackTrace();
        }
        catch (InvalidKeyException e) 
        {
            System.out.println("InvalidKeyException encountered.");
            e.printStackTrace();
        }
        catch (StorageException e) 
        {
            System.out.println("StorageException encountered.");
            e.printStackTrace();
        }
        catch (Exception e) 
        {
            System.out.println("Exception encountered.");
            e.printStackTrace();
        }


    }

}

ImportantImportant
Ensure that you keep the container shared access signature secure; anyone that has a shared access signature with a valid time period can access the container. Similarly, anyone that has a blob shared access signature with a valid time period can access the blob.

In addition to creating a shared access signature on a container, you could create a shared access signature for a blob, using the CloudBlob.generateSharedAccessSignature method.

Once a shared access signature for a container is created, a client can use it to access the container. Similarly, once a shared access signature is created for a blob, a client can use it to access the blob. The following code shows how to use a container shared access signature to upload a blob. This code assumes you’ve already created a shared access signature on the container and securely provided it to the client. The container name is passed in as the first parameter, the container shared access signature is passed in as the second parameter, and an instance of the CloudBlobClient is passed in as the third parameter.

// Create an image, c:\myimages\image1.jpg, prior to running this code.
// Alternatively, change the value used by the FileInputStream constructor 
// to use a different image path and file that you have already created.
public static void MyUploadBlob(String containerName, String containerSAS, CloudBlobClient blobClient)
     throws URISyntaxException, StorageException, FileNotFoundException, IOException
{

    String blobName = "image1.jpg";  // Name as it will appear in blob storage.
    String localFileName = "c:\\myimages\\image1.jpg";  // Path and name of the local file.

    // Append the container name, blob name, and
    // shared access signature to the URI.
    URI uri = new URI(blobClient.getEndpoint().toString() + "/" +
                      containerName + "/" + 
                      blobName + 
                      "?" + 
                      containerSAS);

    // Create a blob using the URI that contains the shared access signature.
    CloudBlockBlob sasBlob = new CloudBlockBlob(uri, blobClient);
    
    // Get a file reference to the local file.
    File fileReference = new File (localFileName);
    
    // Upload the file to the blob.
    sasBlob.upload(new FileInputStream(fileReference), fileReference.length());

}

See Also

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft