Azure Storage – Part 5 – Read BLOB data using SAS Token

Santosh Gaikwad
Latest posts by Santosh Gaikwad (see all)

<<Part 1    <<Part 2    <<Part 3    <<Part 4   >> Azure    Download code

How a shared access signature works

A shared access signature is a signed URI that points to one or more storage resources and includes a token that contains a special set of query parameters. The token indicates how the resources may be accessed by the client. One of the query parameters, the signature, is constructed from the SAS parameters and signed with the account key. This signature is used by Azure Storage to authenticate.

The SAS token is a string you generate on the client side. A SAS token you generate with the storage client library. You can create an unlimited number of SAS tokens on the client side.

 

When a client provides a SAS URI to Azure Storage as part of a request, the service checks the SAS parameters and signature to verify that it is valid for authenticating the request. If the service verifies that the signature is valid, then the request is authenticated. Otherwise, the request is declined with error code 403 (Forbidden).

 

For more information about how blobs work please refer articles <<Part 1    <<Part 2    <<Part 3    <<Part 4

How use Share Access Signature?

As owner of the blob, you need to create shared access signature and provide the same to your clients.

Step 1: Create SAS token

The following code example creates an account SAS that is valid for the Blob and File services, and gives the client permissions read, write, and list permissions to access service-level APIs. The account SAS restricts the protocol to HTTPS, so the request must be made with HTTPS.

Create console application and paste following code, to know about how to get the connection string of blob and installing nuget package, please refer article Part 3. Run the application to get SAS token.

Following application creates SAS token for the BLOB file MyContacts.txt

Blob File MyContacts
Blob File MyContacts

Following is the content of file.

MyContacts File
MyContacts File

Code to generate BLOB storage URI with SAS Token

File: Program.cs

using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
           Console.WriteLine(GetBlobSasUri());
            Console.ReadLine();
        }

        static string GetBlobSasUri()
        {
            // To create the account SAS, you need to use your shared key credentials. Modify for your account.
            const string ConnectionString = "DefaultEndpointsProtocol=https;AccountName=sharedkeys;AccountKey=oO/+Pe+K4AvHL+R/svio2NcNrcZ0gDg/ag+oDWI5KfOslZgyqAsMe5RWzKL5tKzqCjGKU9RG2a0oyhksAqH3NA==;EndpointSuffix=core.windows.net";
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConnectionString);
            CloudBlobClient blobClientWithSAS = storageAccount.CreateCloudBlobClient();
            CloudBlobContainer container = blobClientWithSAS.GetContainerReference("mynewcontainer");

            //Get a reference to a blob within the container.
            CloudBlockBlob blob = container.GetBlockBlobReference("MyContacts.txt");

            //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 = DateTimeOffset.UtcNow.AddMinutes(-5);
            sasConstraints.SharedAccessExpiryTime = DateTimeOffset.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;
        }
    }
}

Application returns following URI

https://sharedkeys.blob.core.windows.net/mynewcontainer/MyContacts.txt?sv=2016-05-31&sr=b&sig=a3AqebhPpI%2FnpTTYHUEzNAR4WWMYf099vxWvAGEUoP8%3D&st=2017-06-18T12%3A07%3A33Z&se=2017-06-19T12%3A12%3A33Z&sp=rw

Application returns SAS URI
Application returns SAS URI

Step 2: Use SAS token in Client’s or 3rd party application code

Once you create SAS token at your end, you need to provide that storage account name and token to your clients or 3rd parties who want to consume your blob. I have used console application to read content of blob using SAS token.

Code to consume BLOB storage from Client App using SAS Token 

File: Program.cs

using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure.Storage.Shared.Protocol;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ThirdPartyApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            string sasToken = "https://sharedkeys.blob.core.windows.net/mynewcontainer/MyContacts.txt?sv=2016-05-31&sr=b&sig=a3AqebhPpI%2FnpTTYHUEzNAR4WWMYf099vxWvAGEUoP8%3D&st=2017-06-18T12%3A07%3A33Z&se=2017-06-19T12%3A12%3A33Z&sp=rw";
            UseAccountSAS(sasToken);
            Console.ReadLine();
        }

        static void UseAccountSAS(string sasToken)
        {
            CloudBlob blobsas = new CloudBlob(new Uri(sasToken));
            MemoryStream msRead = new MemoryStream();
            using (msRead)
            {
                blobsas.DownloadToStream(msRead);
                msRead.Position = 0;
                using (StreamReader reader = new StreamReader(msRead, true))
                {
                    string line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        Console.WriteLine(line);
                    }
                }
            }
        }
    }
}

Run the application and you will see the content of file on the screen.

Client Application returns content of BLOB file
Client Application returns content of BLOB file

<<Part 1    <<Part 2    <<Part 3    <<Part 4    >> Azure   Download code


Check Articles From Categories      Health and Parenting      Inspiring Stories      Technology      Microsoft Azure      SharePoint O365

Leave a Reply

Your email address will not be published. Required fields are marked *