Created
December 14, 2018 08:09
-
-
Save arieffikhrie/1161138352aa7bf8d07f5420e6056d6a to your computer and use it in GitHub Desktop.
Azure oauth access token c#
This file contains 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
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