Created
May 1, 2019 00:37
-
-
Save emregulcan/067c7c31a265959485991c299f68cfdb to your computer and use it in GitHub Desktop.
Dynamics 365 CE (CRM) Web API Authentication by using OAuth Client Credentials Grant
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
public string RetrieveAuthToken(string authorityURI, string d365Url, string clientId, string clientSecret) | |
{ | |
string result = string.Empty; | |
using (HttpClient httpClient = new HttpClient()) | |
{ | |
string tokenUrl = $"{authorityURI}/oauth2/token"; | |
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, tokenUrl); | |
request.Content = 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", d365Url), | |
}); | |
var response = httpClient.SendAsync(request).GetAwaiter().GetResult(); | |
var content = response.Content.ReadAsStringAsync(); | |
var parsedData = JValue.Parse(content.Result); | |
result = parsedData["access_token"].ToString(); | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This code snippet assumes "authorityURI" parameter is like https://login.microsoftonline.com/{TENANT_ID_GUID} and add "oauth2/token" suffix at the end of this URI.