Skip to content

Instantly share code, notes, and snippets.

@buchizo
Last active April 27, 2019 07:40
Show Gist options
  • Save buchizo/18a66af3e17e2767d51613e33d75195f to your computer and use it in GitHub Desktop.
Save buchizo/18a66af3e17e2767d51613e33d75195f to your computer and use it in GitHub Desktop.
call Azure ARM REST API using user token via devicelogin
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System;
using System.Net.Http;
using System.Threading.Tasks;
namespace ConsoleApp11
{
class Program
{
static void Main(string[] args)
{
Task.Run(() => GetToken()).Wait();
}
private const string ARMClientID = "1950a258-227b-4e31-a9cf-717495945fc2"; // <- this is Azure PowerShell client id
static async Task GetToken()
{
var authContextURL = "https://login.windows.net/common/";
var authenticationContext = new AuthenticationContext(authContextURL);
var deviceresult = await authenticationContext.AcquireDeviceCodeAsync("https://management.azure.com/", ARMClientID);
Console.WriteLine(deviceresult.VerificationUrl);
Console.WriteLine("device code: {0}", deviceresult.UserCode);
var token = await authenticationContext.AcquireTokenByDeviceCodeAsync(deviceresult);
// call to Azure ARM REST API using user token
var req = new HttpRequestMessage()
{
Method = HttpMethod.Get,
RequestUri = new Uri("https://management.azure.com/providers/Microsoft.Features/operations?api-version=2015-12-01")
};
req.Headers.Add("Authorization", token.CreateAuthorizationHeader());
var client = new HttpClient();
var res = await client.SendAsync(req);
Console.WriteLine("-----------------------");
Console.WriteLine(res.StatusCode);
var body = await res.Content.ReadAsStringAsync();
Console.WriteLine(body);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment