Paul John

Paul John

  • NA
  • 6
  • 590

Generate Access Token For Dynamics 365 Single Tenant Server To Server

Nov 9 2020 9:16 AM
Hi Experts,
 
I am new to console app . using OAuth, I am trying to connect to crm and retrieve all accounts records as show in below code.
  1. using Microsoft.IdentityModel.Clients.ActiveDirectory;  
  2. using System;  
  3. using System.Net.Http;  
  4. using System.Net.Http.Headers;  
  5. using System.Text;  
  6. using System.Threading.Tasks;  
  7. using System.Net.Sockets;  
  8. namespace CRMConnection  
  9. {  
  10. class Program  
  11. {  
  12. static void Main(string[] args)  
  13. {  
  14. var accounts = CrmRequest(HttpMethod.Get,"crmurl/api/data/v9.1/accounts").Result.Content.ReadAsStringAsync();  
  15. }  
  16. /// Method-to-generate-Access-Token  
  17. public static async Task<string> AccessTokenGenerator()  
  18. {  
  19. string clientId = "ID";  
  20. string clientSecret = "Secret code";  
  21. string authority = "login.microsoft.com/tenantID/oauth2/v2.0/token";  
  22. string resourceUrl = "CRMUrl";  
  23. var credentials = new ClientCredential(clientId, clientSecret);  
  24. var authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(authority);  
  25. var result = await authContext.AcquireTokenAsync(resourceUrl, credentials);  
  26. return result.AccessToken;  
  27. }  
  28. public static async Task<HttpResponseMessage> CrmRequest(HttpMethod httpMethod, string requestUri, string body = null)  
  29. {  
  30. var accessToken = await AccessTokenGenerator();  
  31. var client = new HttpClient();  
  32. var msg = new HttpRequestMessage(httpMethod, requestUri);  
  33. msg.Headers.Add("OData-MaxVersion""4.0");  
  34. msg.Headers.Add("OData-Version""4.0");  
  35. msg.Headers.Add("Prefer""odata.include-annotations=\"*\"");  
  36. // Passing AccessToken in Authentication header  
  37. msg.Headers.Add("Authorization", $"Bearer {accessToken}");  
  38. if (body != null)  
  39. msg.Content = new StringContent(body, UnicodeEncoding.UTF8, "application/json");  
  40. return await client.SendAsync(msg);  
  41. }  
  42. }  
  43. }  
I am getting below error: The program '[24580] CRMConnection.exe' has exited with code 0 (0x0).
 
Reason: I need to check the roles in another call and assign system admin access. can anyone please provide the code on how to achieve this?

Answers (1)