If you intend to use the WindowsAzure.Storage library with .Net Core you’ll hit a"compatibility wall" trying to make it work.
So how can we use .Net Core to Create Azure Blob Storage SAS Keys?
Add the System.Security.Cryptography.Algorithms dependency
Add the following dependency in your project.json file
1 "System.Security.Cryptography.Algorithms": "4.2.0"
Create a StorageEntitySas class to hold the SAS key
The following class will hold de blob Uri and the SAS credentials.
1 public struct StorageEntitySas
2 {
3 public string Credentials;
4 public Uri BlobUri;
5 public string Name;
6 }
Create the following methods
I’ve created the GetSharedAccessSignature to return a write only SAS key for the blob. But you can easily change it to add more permissions.
1 /// <summary>
2 /// Creates a write only access SAS key for the given blob.
3 /// </summary>
4 ///
5 ///
6 ///
7 ///
8 ///
9 ///
10 /// <returns>SAS credentials for ther blob.</returns>
11 private StorageEntitySas GetSharedAccessSignature(
12 string accountName,
13 string blobContainer,
14 string blobName,
15 string key,
16 DateTimeOffset sharedAccessStartTime,
17 DateTimeOffset sharedAccessExpiryTime)
18 {
19 var canonicalNameFormat = $"/blob/{accountName}/{blobContainer}/{blobName}";
20 var st = sharedAccessStartTime.UtcDateTime.ToString("yyyy-MM-ddTHH:mm:ssZ");
21 var se = sharedAccessExpiryTime.UtcDateTime.ToString("yyyy-MM-ddTHH:mm:ssZ");
22 var sasVersion = "2015-07-08";
23
24 string stringToSign = string.Format("{0}\n{1}\n{2}\n{3}\n{4}\n{5}\n{6}\n{7}\n{8}\n{9}\n{10}\n{11}\n{12}", new object[]
25 {
26 "w", // Write only permission.
27 st,
28 se,
29 canonicalNameFormat,
30 string.Empty,
31 string.Empty,
32 string.Empty,
33 sasVersion,
34 string.Empty,
35 string.Empty,
36 string.Empty,
37 string.Empty,
38 string.Empty
39 });
40
41 var sas = GetHash(stringToSign, key);
42
43 var credentials =
44 $"?sv={sasVersion}&sr=b&sig={UrlEncoder.Default.Encode(sas)}&st={UrlEncoder.Default.Encode(st)}&se={UrlEncoder.Default.Encode(se)}&sp=w";
45
46 return new StorageEntitySas
47 {
48 BlobUri = new Uri($"https://{accountName}.blob.core.windows.net/{blobContainer}/{blobName}"),
49 Credentials = credentials,
50 Name = blobName
51 };
52 }
53
54 private string GetHash(string stringToSign, string key)
55 {
56 byte[] keyValue = Convert.FromBase64String(key);
57
58 using (HMACSHA256 hmac = new HMACSHA256(keyValue))
59 {
60 return Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));
61 }
62 }
Call the GetSharedAccessSignature method.
1 var blobSas = GetSharedAccessSignature(accountName, blobContainer, blobName, storageKey, sharedAccessStartTime, sharedAccessExpiryTime);
Find a full working sample here: https://github.com/cmendible/dotnetcore.samples/tree/main/cloud.design.patterns/valet.key/valet.key.server
Hope it helps!!!
Comments