Last active
October 4, 2018 21:58
-
-
Save ljtill/f0a081b555cd222ad86618d90d998549 to your computer and use it in GitHub Desktop.
Provides the ability to retrieve an Access Token via REST API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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