Thursday, 25 August 2016

Generate SAS token to access Blobs/Container from Azure storage

Technology: Azure Storage, SAS token 

Name Spaces Required: 


using Microsoft.WindowsAzure.Storage.Blob;


            string AccountName = "Azure storage Name";
            string AccountKey = "Azure storage key";
            string ContainerName = "Container Name";

            string storageConnectionString = string.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}", AccountName, AccountKey);
            var blobClient = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(storageConnectionString).CreateCloudBlobClient();
            Microsoft.WindowsAzure.Storage.Blob.CloudBlobContainer _BlobContainer = blobClient.GetContainerReference(ContainerName);
            CloudBlockBlob blob = _BlobContainer.GetBlockBlobReference("Blob Name"); //Enter blob name for which SAS token need to be generated
            string url = "";
             string token=GetContainerSasUri(_BlobContainer); // container level SAS token
             url = await GetBlobSasUri(_BlobContainer); // blob level SAS token 


       static string GetContainerSasUri(CloudBlobContainer container)
        {
            //Set the expiry time and permissions for the container.
            //In this case no start time is specified, so the shared access signature becomes valid immediately.
            SharedAccessBlobPolicy sasConstraints = new SharedAccessBlobPolicy();
            sasConstraints.SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24);
            sasConstraints.Permissions = SharedAccessBlobPermissions.Write | SharedAccessBlobPermissions.List;

            //Generate the shared access signature on the container, setting the constraints directly on the signature.
            string sasContainerToken = container.GetSharedAccessSignature(sasConstraints);

            //Return the URI string for the container, including the SAS token.
            return container.Uri + sasContainerToken;
        }


        static async Task<string> GetBlobSasUri(CloudBlobContainer container)
        {
            //Get a reference to a blob within the container.
            CloudBlockBlob blob = container.GetBlockBlobReference(ImageName);

            //Upload text to the blob. If the blob does not yet exist, it will be created.
            //If the blob does exist, its existing content will be overwritten.
            //string blobContent = "This blob will be accessible to clients via a Shared Access Signature.";
            //MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(blobContent));
            //ms.Position = 0;
            //using (ms)
            //{
            //    await blob.UploadFromStreamAsync(ms);
            //}
            //byte[] imagebytes=null;
            //await blob.DownloadToByteArrayAsync(imagebytes, 0);
            


            //Set the expiry time and permissions for the blob.
            //In this case the start time is specified as a few minutes in the past, to mitigate clock skew.
            //The shared access signature will be valid immediately.
            SharedAccessBlobPolicy sasConstraints = new SharedAccessBlobPolicy();
            sasConstraints.SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-5);
            sasConstraints.SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24);
            sasConstraints.Permissions = SharedAccessBlobPermissions.Read | SharedAccessBlobPermissions.Write;

            //Generate the shared access signature on the blob, setting the constraints directly on the signature.
            string sasBlobToken = blob.GetSharedAccessSignature(sasConstraints);

            //Return the URI string for the container, including the SAS token.
            return blob.Uri + sasBlobToken;
        }

No comments:

Post a Comment