Last active
May 27, 2017 17:00
-
-
Save r4hulp/4fd328a09d1fee4d1e7f1bd35fa83ff4 to your computer and use it in GitHub Desktop.
Headless communcation to Dynamics CRM using application user
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
| /// <summary> | |
| /// Headless communication to dynamics CRM using application user. | |
| /// More information at : http://www.wrapcode.com/server-authentication-dynamics-crm/ | |
| /// This is just a sample code, there are way better ways to achieve the same. Did not want to spend much time on code snippet. | |
| /// </summary> | |
| public static async Task HeadlessAuthenticationPOC() | |
| { | |
| var clientCreds = new ClientCredential("{AZURE_AD_APP_ID}", "{AZURE_AD_APP_SECRET}"); | |
| AuthenticationResult authResult = null; | |
| // Call sample API | |
| try | |
| { | |
| authResult = await authContext.AcquireTokenAsync("https://{{TENANT}}.crm4.dynamics.com", clientCreds); | |
| // Add the access token to the authorization header of the request. | |
| if(authResult == null) | |
| return; | |
| httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken); | |
| HttpResponseMessage response = await httpClient.GetAsync("https://{{TENANT}}.crm4.dynamics.com/api/data/v8.1/contacts?$top=1"); | |
| if (response.IsSuccessStatusCode) | |
| { | |
| // Read the response and output it to the console. | |
| string s = await response.Content.ReadAsStringAsync(); | |
| } | |
| else | |
| { | |
| Console.WriteLine("Failed to retrieve contact \nError: {0}\n", response.ReasonPhrase); | |
| } | |
| } | |
| catch (Exception ex) | |
| { | |
| _logger.Fatal(ex); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment