Skip to content

Instantly share code, notes, and snippets.

@ljtill
Last active October 4, 2018 21:58
Show Gist options
  • Select an option

  • Save ljtill/f0a081b555cd222ad86618d90d998549 to your computer and use it in GitHub Desktop.

Select an option

Save ljtill/f0a081b555cd222ad86618d90d998549 to your computer and use it in GitHub Desktop.
Provides the ability to retrieve an Access Token via REST API
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;
namespace Example
{
class Program
{
private static readonly HttpClient client = new HttpClient();
static void Main(string[] args)
{
string tenantId = "";
string clientId = "";
string clientSecret = "";
HttpResponseMessage response = null;
string accessToken = "";
FormUrlEncodedContent body = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("grant_type", "client_credentials"),
new KeyValuePair<string, string>("client_id", clientId),
new KeyValuePair<string, string>("client_secret", clientSecret),
new KeyValuePair<string, string>("resource", "https://management.azure.com/")
});
client.BaseAddress = new Uri("https://login.microsoftonline.com/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
try
{
response = client.PostAsync((tenantId + "/oauth2/token"), body).Result;
} catch (Exception ex)
{
Console.WriteLine(ex);
}
if (response.IsSuccessStatusCode)
{
var content = response.Content.ReadAsStringAsync().Result;
accessToken = JsonConvert.DeserializeObject<Response>(content).access_token;
}
}
}
public class Response
{
public string token_type { get; set; }
public string expires_in { get; set; }
public string ext_expires_in { get; set; }
public string expires_on { get; set; }
public string not_before { get; set; }
public string resource { get; set; }
public string access_token { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment