Skip to content

Instantly share code, notes, and snippets.

@arieffikhrie
Created December 14, 2018 08:09
Show Gist options
  • Save arieffikhrie/1161138352aa7bf8d07f5420e6056d6a to your computer and use it in GitHub Desktop.
Save arieffikhrie/1161138352aa7bf8d07f5420e6056d6a to your computer and use it in GitHub Desktop.
Azure oauth access token c#
string azureLoginOauthUri = "https://login.microsoftonline.com/" + _tenantID + "/oauth2/token";
string azureLoginResource = HttpUtility.UrlEncode(AuthenticationContextResource);
string azurePostBody = "grant_type=client_credentials&client_id=" + _applicationID + "&client_secret=" + _applicationSecret + "&resource=" + azureLoginResource;
HttpRequestMessage httpRequestMessage = new HttpRequestMessage()
{
RequestUri = new Uri(azureLoginOauthUri),
Method = HttpMethod.Post,
Content = new StringContent(azurePostBody, Encoding.UTF8, "application/x-www-form-urlencoded"),
Headers =
{
{ HttpRequestHeader.ContentType.ToString(), "application/x-www-form-urlencoded" }
}
};
HttpResponseMessage response = await _httpClient
.SendAsync(httpRequestMessage)
.ConfigureAwait(continueOnCapturedContext: false);
if (response.StatusCode != HttpStatusCode.OK)
{
throw new System.InvalidOperationException("Failed to obtain the JWT token");
}
string responseContent = await response.Content.ReadAsStringAsync();
JObject contentObject = JObject.Parse(responseContent);
string accessToken = (string)contentObject["access_token"];
return accessToken;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment