Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save emregulcan/067c7c31a265959485991c299f68cfdb to your computer and use it in GitHub Desktop.
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
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;
}
@emregulcan
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment