Azure

Generate SAS Token For Azure Blob Storage Utilizing Managed Identification

Shared Entry Signature (SAS) token is used to grant restricted entry to blob for nameless customers.  This entry might be timebound to a particular time vary and actions like learn, write, or extra to a particular file held inside blob storage.

This text demonstrates the way to generate consumer delegation shared entry signature (SAS) tokens for an Azure Blob. As we all know, managed identities for Azure assets are extremely really helpful wherever potential as this can be a safety finest observe. Right here, We’ll allow managed identification for an Azure storage account from Entry Management (IAM). Then we are going to generate a consumer delegation SAS token utilizing Default Azure Credential. This SAS token will guarantee safe and delegated entry to the blob current within the storage container.

For demonstration objective, we are going to create an online utility the place some photos are accessed from azure blob storage. To entry the picture from the storage container, we are going to generate a consumer delegation SAS token. Utilizing this SAS token, we are going to entry picture or media recordsdata into our web site.

Let’s perceive step-by-step strategy to reaching this. Right here I’m assuming that now we have an current utility the place we try to entry blobs utilizing SAS. In my case, I’ve a easy web site construct in .NET and storage account created with container identify “media” and uploaded a picture there within the container.

Step 1 – Set up Guget packages

Beneath packages want to put in in your utility. That is required for MSI and Blob operation.

<PackageReference Embody="Azure.Identification" Model="1.5.0" />
<PackageReference Embody="Azure.Storage.Blobs" Model="12.10.0" />

Step 2 – Producing a Consumer Delegation SAS

We will simply connect with Azure storage account utilizing Azure AD Credentials utilizing DefaultAzureCredential helper class. Let’s create blob service consumer with Azure AD credentials after which create a consumer delegation key for the Blob service that is legitimate for two hours. Right here, I’m studying StorageAccountName and ContainerName from appsettings configuration.

public IActionResult Index() 
{
    var storageAccountName = _configuration.GetValue<string>("StorageAccountName");
    var saUri = $"https://{storageAccountName}.blob.core.home windows.web";
    // Create a brand new Blob service consumer with Azure AD credentials.
    var blobServiceClient = new BlobServiceClient(new Uri(saUri), new DefaultAzureCredential());
    var blobContainerClient = blobServiceClient.GetBlobContainerClient(_configuration.GetValue<string>("ContainerName"));
    var blobClient = blobContainerClient.GetBlobClient("azure.jpg"); // blob identify
    // Get a consumer delegation key for the Blob service that is legitimate for two hours.
    var userDelegationKey =  blobServiceClient.GetUserDelegationKey(DateTimeOffset.UtcNow,
                                                                    DateTimeOffset.UtcNow.AddHours(2));
    var sasBuilder = new BlobSasBuilder()
    {
        BlobContainerName = blobClient.BlobContainerName,
        BlobName = blobClient.Title, 
        Useful resource = "b", // b for blob, c for container
        StartsOn = DateTimeOffset.UtcNow,
        ExpiresOn = DateTimeOffset.UtcNow.AddHours(2),
    };

    sasBuilder.SetPermissions(BlobSasPermissions.Learn); // learn permissions
    // Add the SAS token to the container URI.
    var blobUriBuilder = new BlobUriBuilder(blobClient.Uri)
    {
        Sas = sasBuilder.ToSasQueryParameters(userDelegationKey,blobServiceClient.AccountName)
    };

    ViewData["imgSrc"] = blobUriBuilder.ToUri().ToString();
    return View();
}

Step 3 – Add function task in Storage Account

Now go to storage account -> Entry Management (IAM) -> + Add -> Add Position Task -> Sreach for Position like “Storage Blob Information Reader” -> Choose members then assign function that consumer.

In my case, I granted RBAC for a consumer referred to as “msi consumer”.

Step 4 – Arrange Azure Service Authentication account in VS

Go to Instruments -> Choices -> Azure Service Authentication. Select an account that has given permission to manged identification in earlier step.

Set up Azure Service Authentication account in VS

Generally it’s inflicting difficulty as we aren’t choosing the precise account. That’s could cease you to check it regionally attributable to beneath error. If we choose right account which is having correct permission granted in earlier step, we will keep away from this difficulty.

Set up Azure Service Authentication account in VS

Step 5 – Check in localhost

As soon as the whole lot is setup regionally and we select right Azure Service Authentication, we will check our logic regionally. In my case, I’m accessing a picture of my utility from storage.

If we attempt to hit on to the URL with out SAS, it’s will present an error – which is predicted as Blob public entry is disabled, and we don’t wish to nameless to entry it.

Superior! We will see that how simply we will entry blob utilizing SAS token. An fascinating a part of it, we didn’t use any connection string or entry key to get it carried out. That is the great thing about MSI.

Now after deployment of utility in azure app service, allow system assigned Identification for app service. And add that Object Id of Identification to storage account function task. All set! Now deployed app will work because it was working regionally.

Pleased Studying!

Show More

Related Articles

Leave a Reply

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

Back to top button