Skip to content

Instantly share code, notes, and snippets.

@rajinders
Created December 16, 2014 03:36
Show Gist options
  • Save rajinders/4f3551e5d2922544b7c4 to your computer and use it in GitHub Desktop.
Save rajinders/4f3551e5d2922544b7c4 to your computer and use it in GitHub Desktop.
How to create authentication header for Azure. This code came from Azure Resource manager training by Kevin Lam and David Tesar. This willl be help to any who wants to use Azure REST API and needs to generate authentication header
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
// you need to add project references to both Microsoft.IdentityModel.Clients.ActiveDirectory and
// Microsoft.IdentityModel.Clients.ActiveDirectory.WinForms
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System.Threading;
namespace GenerateAzureAuthHeader
{
class Program
{
static void Main(string[] args)
{
var tenantId = "your tenant id"; // Use Get-AzureAccount cmdlet to get tenant id
var clientId = "1950a258-227b-4e31-a9cf-717495945fc2";
var authUrl = "https://login.windows.net";
var header = GetAuthorizationHeader(tenantId, authUrl, clientId);
Console.Write(header);
}
private static string GetAuthorizationHeader(string tenantId, string authUrlHost, string clientId)
{
AuthenticationResult result = null;
var thread = new Thread(() =>
{
try
{
var authUrl = String.Format(authUrlHost + "/{0}", tenantId);
var context = new AuthenticationContext(authUrl);
result = context.AcquireToken(
resource: "https://management.core.windows.net/",
clientId: clientId,
redirectUri: new Uri("urn:ietf:wg:oauth:2.0:oob"),
promptBehavior: PromptBehavior.Auto);
}
catch (Exception threadEx)
{
Console.WriteLine(threadEx.Message);
}
});
thread.SetApartmentState(ApartmentState.STA);
thread.Name = "AcquireTokenThread";
thread.Start();
thread.Join();
return result.CreateAuthorizationHeader();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment