Authorization
Authorization header is used to authenticate Azure services via Rest API. Every request to the Azure storage service must be authenticated. This authentication scheme supports Azure storage services like blobs, queues, tables, and files.
The header looks like the below scheme,
x-ms-date: date_and_time
Authorization:azure_storage_account_name:signature
Shared Key Authentication
Here I used the Shared Key Lite authentication scheme. Shared Key authorization relies on your account access keys and other parameters to produce an encrypted signature string that is passed on the request in the Authorizationheader. The actual sample of Shared Key authentication will be,
Method: GET
ContentType: application/json
X-ms-date :Fri, 17 Aug 2018 12:18:16 GMT
Authorization: SharedKeyLite testaccount008:uay+rilMVayH/Sdsfd8X+a3fL8k/NxCnIePdyZSkqvydM=
Authorizationheader is constructed by making a hash-based message authentication code using the
SHA-256 hash
The following is an example of performing the HMACSHA256 hash for the Authorization header,
- using System;
- using System.Text;
- using System.Net;
- using System.Security.Cryptography;
- namespace AzureTablesAuthentication {
- class Program {
- static void Main(string[] args) {
- try {
- string storageAccount = "";
- string accessKey = "";
- string TableName = "";
- string uri = @ "https://" + storageAccount + ".table.core.windows.net/" + resourcePath;
- HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create(uri);
- request.Method = "GET";
- request.ContentType = "application/json";
- request.ContentLength = resourcePath.Length;
- request.Accept = "application/json;odata=nometadata";
- request.Headers.Add("x-ms-date", DateTime.UtcNow.ToString("R", System.Globalization.CultureInfo.InvariantCulture));
- request.Headers.Add("x-ms-version", "2015-12-11");
- request.Headers.Add("Accept-Charset", "UTF-8");
- request.Headers.Add("MaxDataServiceVersion", "3.0;NetFx");
- request.Headers.Add("DataServiceVersion", "1.0;NetFx");
- string stringToSign = request.Headers["x-ms-date"] + "\n";
- stringToSign += "/" + storageAccount + "/" + resourcePath;
- HMACSHA256 hasher = new HMACSHA256(Convert.FromBase64String(accessKey));
- string sAuthTokn = "SharedKeyLite " + storageAccount + ":" + Convert.ToBase64String(hasher.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));
- request.Headers.Add("Authorization", sAuthTokn);
- Console.WriteLine("Authorization Header :", request.Headers["Authorization"]);
- Console.ReadLine();
- } catch (Exception ex) {
- throw ex;
- }
- }
- }
- }
That's it. Now run the application, go to Debug menu and click on Start without Debugging, or press F5. This will open the console and display the following result.
I hope you have learned how to create an authorization header for authenticating Azure storage services using C#. Feel free to fill up the comment box below, if you need any assistance.