I want to generate SAS URL dynamically via C# code for Azure Blob Container. Using this SAS URL we must be able to upload the files to the Azure Blob Container. I have tried multiple ways to generate the SAS URL by following the Microsoft docs. But I am always getting AuthorizationResourceTypeMismatch Error or AuthorizationPermissionMismatch.
Error: AuthorizationPermissionMismatch
This request is not authorized to perform this operation using this permission.
private static Uri GetServiceSasUriForContainer(BlobContainerClient containerClient,
string storedPolicyName = null)
{
// Check whether this BlobContainerClient object has been authorized with Shared Key.
if (containerClient.CanGenerateSasUri)
{
// Create a SAS token that's valid for one hour.
BlobSasBuilder sasBuilder = new BlobSasBuilder()
{
BlobContainerName = containerClient.Name,
Resource = "c"
};
if (storedPolicyName == null)
{
sasBuilder.ExpiresOn = DateTimeOffset.UtcNow.AddHours(1);
sasBuilder.SetPermissions(BlobContainerSasPermissions.Read);
}
else
{
sasBuilder.Identifier = storedPolicyName;
}
Uri sasUri = containerClient.GenerateSasUri(sasBuilder);
Console.WriteLine("SAS URI for blob container is: {0}", sasUri);
Console.WriteLine();
return sasUri;
}
else
{
Console.WriteLine(@"BlobContainerClient must be authorized with Shared Key
credentials to create a service SAS.");
return null;
}
}
Error: AuthenticationFailed
Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.
I need this sas url because I use this url in my javascript to upload files into the Azure Blob Container. Can someone help me out achieving this goal?
The reason you're getting this error is because you are creating the SAS token with Read
permission (BlobContainerSasPermissions.Read
).
In order to upload a blob in a container using SAS URL, the SAS token needs either Write
(BlobContainerSasPermissions.Write
) or Create
(BlobContainerSasPermissions.Create
) permission. Please create a SAS token with one of these permissions and you should not get this error.
To learn more about the permissions, please see this link: https://learn.microsoft.com/en-us/rest/api/storageservices/create-service-sas#permissions-for-a-directory-container-or-blob.