question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How do we use GenerateSasUri to create a SAS based on a storage access policy?

See original GitHub issue

Library name and version

Azure.Storage.Blobs 12.14.1

Query/Question

We have code in SQL Server Management Studio to set an access policy on a container and generate a SAS based on that access policy. That SAS is then used as a credential by SQL Server to enable backup to/restore from URL.

I am trying to port the code from the old WindowsAzure.Storage SDK to the new Azure.Storage.Blobs SDK and I can’t find an equivalent way to generate a SAS based on the access policy.

The old code is below. Note that CloudBlobContainer.GetSharedAccessSignature had a override that accepts the SharedAccessBlobPolicy as a parameter. In the new SDK I don’t see any parameters for BlobContainerClient.GenerateSasUri or BlobSasBuilder that are related to the access policy.

/// <summary>
        /// Create Shared Access Policy for container 
        /// Default Accesss permission is Write/List/Read/Delete
        /// </summary>
        /// <param name="container"></param>
        /// <param name="policyName"></param>
        /// <param name="selectedSaredAccessExpiryTime"></param>
        public static string CreateSharedAccessPolicyOnContainer(CloudBlobContainer container, string policyName, DateTime selectedSaredAccessExpiryTime)
        {
            //Create a new stored access policy and define its constraints.
            SharedAccessBlobPolicy sharedAccessPolicyForContainer = new SharedAccessBlobPolicy()
            {
                SharedAccessExpiryTime = selectedSaredAccessExpiryTime,
                Permissions = SharedAccessBlobPermissions.Write | SharedAccessBlobPermissions.List | SharedAccessBlobPermissions.Read | SharedAccessBlobPermissions.Delete
            };

            //Get the container's existing permissions.
            BlobContainerPermissions permissions = container.GetPermissions();
            if (!permissions.SharedAccessPolicies.ContainsKey(policyName))
            {
                //Add the new policy to the container's permissions.
                permissions.SharedAccessPolicies.Add(policyName, sharedAccessPolicyForContainer);
            }
            else
            {
                // if already exists, remove then recreate the policy to get expircy/permission right. 
                SharedAccessBlobPolicy existingSharedAccessPolicyForContainer = new SharedAccessBlobPolicy();
                permissions.SharedAccessPolicies.TryGetValue(policyName, out existingSharedAccessPolicyForContainer);

                permissions.SharedAccessPolicies.Remove(policyName);
                container.SetPermissions(permissions);
                permissions.SharedAccessPolicies.Add(policyName, sharedAccessPolicyForContainer);
            }
            container.SetPermissions(permissions);
            permissions = container.GetPermissions();

            // verify access
            string sharedAccessSignatureForContainer = container.GetSharedAccessSignature(sharedAccessPolicyForContainer).TrimStart('?');
            if (string.IsNullOrEmpty(sharedAccessSignatureForContainer))
            {
                throw new InvalidCredentialException(SR.InvalidCredential);
            }
            return sharedAccessSignatureForContainer;
        }

This is what I’ve got so far for the replacement using the new SDK. What should I replace my container.GenerateSasUri call with to use the access policy I created for the SAS key? As written, this code generates a SAS without the access policy parameter.

        public static string CreateSharedAccessPolicyOnContainer(BlobContainerClient container, string policyName, DateTime selectedSharedAccessExpiryTime)
        {
            //Create a new stored access policy and define its constraints.
            var sharedAccessPolicyForContainer = new BlobSignedIdentifier()
            {
                Id = policyName,
                AccessPolicy = new BlobAccessPolicy()
                {
                    PolicyExpiresOn = selectedSharedAccessExpiryTime,
                    Permissions = "wlrd" // Write | List | Read | Delete
                }
            };

            //Get the container's existing permissions.
            var existingPolicy = container.GetAccessPolicy().Value;
            var permissions = existingPolicy.SignedIdentifiers.ToList();
            var existingPermission = permissions.FindIndex(b => b.Id == policyName);
            if (existingPermission == -1)
            {
                //Add the new policy to the container's permissions.
                permissions.Add(sharedAccessPolicyForContainer);
            }
            else
            {
                permissions[existingPermission] = sharedAccessPolicyForContainer;
            }
            container.SetAccessPolicy(existingPolicy.BlobPublicAccess, permissions);

            // verify access
            string sharedAccessSignatureForContainer = container.GenerateSasUri(Sas.BlobContainerSasPermissions.Write | Sas.BlobContainerSasPermissions.List | Sas.BlobContainerSasPermissions.Delete | Sas.BlobContainerSasPermissions.Read, selectedSharedAccessExpiryTime).Query.TrimStart('?');
            if (string.IsNullOrEmpty(sharedAccessSignatureForContainer))
            {
                throw new InvalidCredentialException(SR.InvalidCredential);
            }
            return sharedAccessSignatureForContainer;
        }

Environment

Visual Studio 2022 with SDK 7 building for .Net 4.7.2

Issue Analytics

  • State:closed
  • Created 7 months ago
  • Comments:5 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
navba-MSFTcommented, Feb 24, 2023

@shueybubbles Could you please refer the sample code snippet provided in this article ? Hope this helps.

0reactions
shueybubblescommented, Feb 24, 2023

that works. thx

Read more comments on GitHub >

github_iconTop Results From Across the Web

Grant limited access to data with shared access signatures ...
Learn about using shared access signatures (SAS) to delegate access to Azure Storage resources, including blobs, queues, tables, and files.
Read more >
How to Generate an Azure SAS Token to Access Storage ...
To create a token via the Azure portal, first, navigate to the storage account you'd like to access under the Settings section then...
Read more >
Generate SAS Token For Azure Blob Storage Using ...
This article demonstrates how to generate user delegation shared access signature (SAS) tokens for an Azure Blob.
Read more >
c# - How do you grant access to a container using an ...
If you are generating a SAS Token on the blob container, you will use GenerateSasUri method and specify the access policy id (signed...
Read more >
Stored Access Policy Vs Shared Access Signature (SAS)
#azure #microsoft #shared # SAS #revoking # generate # accesspolicy # storage #storageaccount Please like the video, subscribe to see more, ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found