├── .gitignore ├── LICENSE ├── README.md ├── StorageRestApiAuth.sln └── StorageRestApiAuth ├── App.config ├── AzureStorageAuthenticationHelper.cs ├── Program.cs ├── Properties └── AssemblyInfo.cs └── StorageRestApiAuth.csproj /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | x64/ 19 | x86/ 20 | bld/ 21 | [Bb]in/ 22 | [Oo]bj/ 23 | [Ll]og/ 24 | 25 | # Visual Studio 2015 cache/options directory 26 | .vs/ 27 | # Uncomment if you have tasks that create the project's static files in wwwroot 28 | #wwwroot/ 29 | 30 | # MSTest test Results 31 | [Tt]est[Rr]esult*/ 32 | [Bb]uild[Ll]og.* 33 | 34 | # NUNIT 35 | *.VisualState.xml 36 | TestResult.xml 37 | 38 | # Build Results of an ATL Project 39 | [Dd]ebugPS/ 40 | [Rr]eleasePS/ 41 | dlldata.c 42 | 43 | # DNX 44 | project.lock.json 45 | artifacts/ 46 | 47 | *_i.c 48 | *_p.c 49 | *_i.h 50 | *.ilk 51 | *.meta 52 | *.obj 53 | *.pch 54 | *.pdb 55 | *.pgc 56 | *.pgd 57 | *.rsp 58 | *.sbr 59 | *.tlb 60 | *.tli 61 | *.tlh 62 | *.tmp 63 | *.tmp_proj 64 | *.log 65 | *.vspscc 66 | *.vssscc 67 | .builds 68 | *.pidb 69 | *.svclog 70 | *.scc 71 | 72 | # Chutzpah Test files 73 | _Chutzpah* 74 | 75 | # Visual C++ cache files 76 | ipch/ 77 | *.aps 78 | *.ncb 79 | *.opendb 80 | *.opensdf 81 | *.sdf 82 | *.cachefile 83 | *.VC.db 84 | *.VC.VC.opendb 85 | 86 | # Visual Studio profiler 87 | *.psess 88 | *.vsp 89 | *.vspx 90 | *.sap 91 | 92 | # TFS 2012 Local Workspace 93 | $tf/ 94 | 95 | # Guidance Automation Toolkit 96 | *.gpState 97 | 98 | # ReSharper is a .NET coding add-in 99 | _ReSharper*/ 100 | *.[Rr]e[Ss]harper 101 | *.DotSettings.user 102 | 103 | # JustCode is a .NET coding add-in 104 | .JustCode 105 | 106 | # TeamCity is a build add-in 107 | _TeamCity* 108 | 109 | # DotCover is a Code Coverage Tool 110 | *.dotCover 111 | 112 | # NCrunch 113 | _NCrunch_* 114 | .*crunch*.local.xml 115 | nCrunchTemp_* 116 | 117 | # MightyMoose 118 | *.mm.* 119 | AutoTest.Net/ 120 | 121 | # Web workbench (sass) 122 | .sass-cache/ 123 | 124 | # Installshield output folder 125 | [Ee]xpress/ 126 | 127 | # DocProject is a documentation generator add-in 128 | DocProject/buildhelp/ 129 | DocProject/Help/*.HxT 130 | DocProject/Help/*.HxC 131 | DocProject/Help/*.hhc 132 | DocProject/Help/*.hhk 133 | DocProject/Help/*.hhp 134 | DocProject/Help/Html2 135 | DocProject/Help/html 136 | 137 | # Click-Once directory 138 | publish/ 139 | 140 | # Publish Web Output 141 | *.[Pp]ublish.xml 142 | *.azurePubxml 143 | # TODO: Comment the next line if you want to checkin your web deploy settings 144 | # but database connection strings (with potential passwords) will be unencrypted 145 | *.pubxml 146 | *.publishproj 147 | 148 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 149 | # checkin your Azure Web App publish settings, but sensitive information contained 150 | # in these scripts will be unencrypted 151 | PublishScripts/ 152 | 153 | # NuGet Packages 154 | *.nupkg 155 | # The packages folder can be ignored because of Package Restore 156 | **/packages/* 157 | # except build/, which is used as an MSBuild target. 158 | !**/packages/build/ 159 | # Uncomment if necessary however generally it will be regenerated when needed 160 | #!**/packages/repositories.config 161 | # NuGet v3's project.json files produces more ignoreable files 162 | *.nuget.props 163 | *.nuget.targets 164 | 165 | # Microsoft Azure Build Output 166 | csx/ 167 | *.build.csdef 168 | 169 | # Microsoft Azure Emulator 170 | ecf/ 171 | rcf/ 172 | 173 | # Windows Store app package directories and files 174 | AppPackages/ 175 | BundleArtifacts/ 176 | Package.StoreAssociation.xml 177 | _pkginfo.txt 178 | 179 | # Visual Studio cache files 180 | # files ending in .cache can be ignored 181 | *.[Cc]ache 182 | # but keep track of directories ending in .cache 183 | !*.[Cc]ache/ 184 | 185 | # Others 186 | ClientBin/ 187 | ~$* 188 | *~ 189 | *.dbmdl 190 | *.dbproj.schemaview 191 | *.pfx 192 | *.publishsettings 193 | node_modules/ 194 | orleans.codegen.cs 195 | 196 | # Since there are multiple workflows, uncomment next line to ignore bower_components 197 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 198 | #bower_components/ 199 | 200 | # RIA/Silverlight projects 201 | Generated_Code/ 202 | 203 | # Backup & report files from converting an old project file 204 | # to a newer Visual Studio version. Backup files are not needed, 205 | # because we have git ;-) 206 | _UpgradeReport_Files/ 207 | Backup*/ 208 | UpgradeLog*.XML 209 | UpgradeLog*.htm 210 | 211 | # SQL Server files 212 | *.mdf 213 | *.ldf 214 | 215 | # Business Intelligence projects 216 | *.rdl.data 217 | *.bim.layout 218 | *.bim_*.settings 219 | 220 | # Microsoft Fakes 221 | FakesAssemblies/ 222 | 223 | # GhostDoc plugin setting file 224 | *.GhostDoc.xml 225 | 226 | # Node.js Tools for Visual Studio 227 | .ntvs_analysis.dat 228 | 229 | # Visual Studio 6 build log 230 | *.plg 231 | 232 | # Visual Studio 6 workspace options file 233 | *.opt 234 | 235 | # Visual Studio LightSwitch build output 236 | **/*.HTMLClient/GeneratedArtifacts 237 | **/*.DesktopClient/GeneratedArtifacts 238 | **/*.DesktopClient/ModelManifest.xml 239 | **/*.Server/GeneratedArtifacts 240 | **/*.Server/ModelManifest.xml 241 | _Pvt_Extensions 242 | 243 | # Paket dependency manager 244 | .paket/paket.exe 245 | paket-files/ 246 | 247 | # FAKE - F# Make 248 | .fake/ 249 | 250 | # JetBrains Rider 251 | .idea/ 252 | *.sln.iml 253 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Microsoft Corporation. All rights reserved. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. 4 | 5 | To run this project, first fill in your storage account name and storage account key in Program.cs. The sample will list the containers in the storage account. 6 | -------------------------------------------------------------------------------- /StorageRestApiAuth.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 14 4 | VisualStudioVersion = 14.0.25420.1 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "StorageRestApiAuth", "StorageRestApiAuth\StorageRestApiAuth.csproj", "{45E46388-D37A-4CB8-A98E-3D1EBD7F6271}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {45E46388-D37A-4CB8-A98E-3D1EBD7F6271}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {45E46388-D37A-4CB8-A98E-3D1EBD7F6271}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {45E46388-D37A-4CB8-A98E-3D1EBD7F6271}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {45E46388-D37A-4CB8-A98E-3D1EBD7F6271}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | EndGlobal 23 | -------------------------------------------------------------------------------- /StorageRestApiAuth/App.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /StorageRestApiAuth/AzureStorageAuthenticationHelper.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Specialized; 3 | using System.Linq; 4 | using System.Net.Http; 5 | using System.Net.Http.Headers; 6 | using System.Security.Cryptography; 7 | using System.Text; 8 | using System.Web; 9 | 10 | namespace StorageRestApiAuth 11 | { 12 | /// 13 | /// You can take this class and drop it into another project and use this code 14 | /// to create the headers you need to make a REST API call to Azure Storage. 15 | /// 16 | internal static class AzureStorageAuthenticationHelper 17 | { 18 | /// 19 | /// This creates the authorization header. This is required, and must be built 20 | /// exactly following the instructions. This will return the authorization header 21 | /// for most storage service calls. 22 | /// Create a string of the message signature and then encrypt it. 23 | /// 24 | /// The name of the storage account to use. 25 | /// The access key for the storage account to be used. 26 | /// Date/Time stamp for now. 27 | /// The HttpWebRequest that needs an auth header. 28 | /// Provide an eTag, and it will only make changes 29 | /// to a blob if the current eTag matches, to ensure you don't overwrite someone else's changes. 30 | /// Provide the md5 and it will check and make sure it matches the blob's md5. 31 | /// If it doesn't match, it won't return a value. 32 | /// 33 | internal static AuthenticationHeaderValue GetAuthorizationHeader( 34 | string storageAccountName, string storageAccountKey, DateTime now, 35 | HttpRequestMessage httpRequestMessage, string ifMatch = "", string md5 = "") 36 | { 37 | // This is the raw representation of the message signature. 38 | HttpMethod method = httpRequestMessage.Method; 39 | String MessageSignature = String.Format("{0}\n\n\n{1}\n{5}\n\n\n\n{2}\n\n\n\n{3}{4}", 40 | method.ToString(), 41 | (method == HttpMethod.Get || method == HttpMethod.Head) ? String.Empty 42 | : httpRequestMessage.Content.Headers.ContentLength.ToString(), 43 | ifMatch, 44 | GetCanonicalizedHeaders(httpRequestMessage), 45 | GetCanonicalizedResource(httpRequestMessage.RequestUri, storageAccountName), 46 | md5); 47 | 48 | // Now turn it into a byte array. 49 | byte[] SignatureBytes = Encoding.UTF8.GetBytes(MessageSignature); 50 | 51 | // Create the HMACSHA256 version of the storage key. 52 | HMACSHA256 SHA256 = new HMACSHA256(Convert.FromBase64String(storageAccountKey)); 53 | 54 | // Compute the hash of the SignatureBytes and convert it to a base64 string. 55 | string signature = Convert.ToBase64String(SHA256.ComputeHash(SignatureBytes)); 56 | 57 | // This is the actual header that will be added to the list of request headers. 58 | // You can stop the code here and look at the value of 'authHV' before it is returned. 59 | AuthenticationHeaderValue authHV = new AuthenticationHeaderValue("SharedKey", 60 | storageAccountName + ":" + Convert.ToBase64String(SHA256.ComputeHash(SignatureBytes))); 61 | return authHV; 62 | } 63 | 64 | /// 65 | /// Put the headers that start with x-ms in a list and sort them. 66 | /// Then format them into a string of [key:value\n] values concatenated into one string. 67 | /// (Canonicalized Headers = headers where the format is standardized). 68 | /// 69 | /// The request that will be made to the storage service. 70 | /// Error message; blank if okay. 71 | private static string GetCanonicalizedHeaders(HttpRequestMessage httpRequestMessage) 72 | { 73 | var headers = from kvp in httpRequestMessage.Headers 74 | where kvp.Key.StartsWith("x-ms-", StringComparison.OrdinalIgnoreCase) 75 | orderby kvp.Key 76 | select new { Key = kvp.Key.ToLowerInvariant(), kvp.Value }; 77 | 78 | StringBuilder sb = new StringBuilder(); 79 | 80 | // Create the string in the right format; this is what makes the headers "canonicalized" -- 81 | // it means put in a standard format. http://en.wikipedia.org/wiki/Canonicalization 82 | foreach (var kvp in headers) 83 | { 84 | StringBuilder headerBuilder = new StringBuilder(kvp.Key); 85 | char separator = ':'; 86 | 87 | // Get the value for each header, strip out \r\n if found, then append it with the key. 88 | foreach (string headerValues in kvp.Value) 89 | { 90 | string trimmedValue = headerValues.TrimStart().Replace("\r\n", String.Empty); 91 | headerBuilder.Append(separator).Append(trimmedValue); 92 | 93 | // Set this to a comma; this will only be used 94 | // if there are multiple values for one of the headers. 95 | separator = ','; 96 | } 97 | sb.Append(headerBuilder.ToString()).Append("\n"); 98 | } 99 | return sb.ToString(); 100 | } 101 | 102 | /// 103 | /// This part of the signature string represents the storage account 104 | /// targeted by the request. Will also include any additional query parameters/values. 105 | /// For ListContainers, this will return something like this: 106 | /// /storageaccountname/\ncomp:list 107 | /// 108 | /// The URI of the storage service. 109 | /// The storage account name. 110 | /// String representing the canonicalized resource. 111 | private static string GetCanonicalizedResource(Uri address, string storageAccountName) 112 | { 113 | // The absolute path is "/" because for we're getting a list of containers. 114 | StringBuilder sb = new StringBuilder("/").Append(storageAccountName).Append(address.AbsolutePath); 115 | 116 | // Address.Query is the resource, such as "?comp=list". 117 | // This ends up with a NameValueCollection with 1 entry having key=comp, value=list. 118 | // It will have more entries if you have more query parameters. 119 | NameValueCollection values = HttpUtility.ParseQueryString(address.Query); 120 | 121 | foreach (var item in values.AllKeys.OrderBy(k => k)) 122 | { 123 | sb.Append('\n').Append(item).Append(':').Append(values[item]); 124 | } 125 | 126 | return sb.ToString().ToLower(); 127 | 128 | } 129 | } 130 | } 131 | -------------------------------------------------------------------------------- /StorageRestApiAuth/Program.cs: -------------------------------------------------------------------------------- 1 | namespace StorageRestApiAuth 2 | { 3 | using System; 4 | using System.Globalization; 5 | using System.Net; 6 | using System.Net.Http; 7 | using System.Threading; 8 | using System.Threading.Tasks; 9 | using System.Xml.Linq; 10 | 11 | internal static class Program 12 | { 13 | static string StorageAccountName = "YOURSTORAGEACCOUNTNAME"; 14 | static string StorageAccountKey = "YOURSTORAGEACCOUNTKEY"; 15 | 16 | private static void Main() 17 | { 18 | // List the containers in a storage account. 19 | ListContainersAsyncREST(StorageAccountName, StorageAccountKey, CancellationToken.None).GetAwaiter().GetResult(); 20 | 21 | Console.WriteLine("Press any key to continue."); 22 | Console.ReadLine(); 23 | } 24 | 25 | /// 26 | /// This is the method to call the REST API to retrieve a list of 27 | /// containers in the specific storage account. 28 | /// This will call CreateRESTRequest to create the request, 29 | /// then check the returned status code. If it's OK (200), it will 30 | /// parse the response and show the list of containers found. 31 | /// 32 | private static async Task ListContainersAsyncREST(string storageAccountName, string storageAccountKey, CancellationToken cancellationToken) 33 | { 34 | 35 | // Construct the URI. This will look like this: 36 | // https://myaccount.blob.core.windows.net/resource 37 | String uri = string.Format("http://{0}.blob.core.windows.net?comp=list", storageAccountName); 38 | 39 | // Set this to whatever payload you desire. Ours is null because 40 | // we're not passing anything in. 41 | Byte[] requestPayload = null; 42 | 43 | //Instantiate the request message with a null payload. 44 | using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, uri) 45 | { Content = (requestPayload == null) ? null : new ByteArrayContent(requestPayload) }) 46 | { 47 | 48 | // Add the request headers for x-ms-date and x-ms-version. 49 | DateTime now = DateTime.UtcNow; 50 | httpRequestMessage.Headers.Add("x-ms-date", now.ToString("R", CultureInfo.InvariantCulture)); 51 | httpRequestMessage.Headers.Add("x-ms-version", "2017-04-17"); 52 | // If you need any additional headers, add them here before creating 53 | // the authorization header. 54 | 55 | // Add the authorization header. 56 | httpRequestMessage.Headers.Authorization = AzureStorageAuthenticationHelper.GetAuthorizationHeader( 57 | storageAccountName, storageAccountKey, now, httpRequestMessage); 58 | 59 | // Send the request. 60 | using (HttpResponseMessage httpResponseMessage = await new HttpClient().SendAsync(httpRequestMessage, cancellationToken)) 61 | { 62 | // If successful (status code = 200), 63 | // parse the XML response for the container names. 64 | if (httpResponseMessage.StatusCode == HttpStatusCode.OK) 65 | { 66 | String xmlString = await httpResponseMessage.Content.ReadAsStringAsync(); 67 | XElement x = XElement.Parse(xmlString); 68 | foreach (XElement container in x.Element("Containers").Elements("Container")) 69 | { 70 | Console.WriteLine("Container name = {0}", container.Element("Name").Value); 71 | } 72 | } 73 | } 74 | } 75 | } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /StorageRestApiAuth/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("StorageRestApiAuth")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("StorageRestApiAuth")] 13 | [assembly: AssemblyCopyright("Copyright © 2017")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("45e46388-d37a-4cb8-a98e-3d1ebd7f6271")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /StorageRestApiAuth/StorageRestApiAuth.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {45E46388-D37A-4CB8-A98E-3D1EBD7F6271} 8 | Exe 9 | Properties 10 | StorageRestApiAuth 11 | StorageRestApiAuth 12 | v4.5.2 13 | 512 14 | true 15 | 16 | 17 | AnyCPU 18 | true 19 | full 20 | false 21 | bin\Debug\ 22 | DEBUG;TRACE 23 | prompt 24 | 4 25 | 26 | 27 | AnyCPU 28 | pdbonly 29 | true 30 | bin\Release\ 31 | TRACE 32 | prompt 33 | 4 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 62 | --------------------------------------------------------------------------------