Hi,
There are two ways for authenticating one is "User Based Authentication" and second "S2S Authentication".
Here you are giving username and password so try below code :
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace Authentication
{
class Program
{
private static string serviceUrl = "provide the crm url";
private static string clientId = "********************";
private static string userName = "****************";
private static string password = "*********";
static void Main(string[] args)
{
HttpMessageHandler messageHandler;
try
{
messageHandler = new OAuthMessageHandler(serviceUrl, clientId, userName, password,
new HttpClientHandler());
//Create an HTTP client to send a request message to the CRM Web service.
using (HttpClient client = new HttpClient(messageHandler))
{
//Specify the Web API address of the service and the period of time each request
// has to execute.
client.BaseAddress = new Uri(serviceUrl);
client.Timeout = new TimeSpan(0, 2, 0); //2 minutes
client.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
client.DefaultRequestHeaders.Add("OData-Version", "4.0");
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
//Send the WhoAmI request to the Web API using a GET request.
var response = client.GetAsync("https://********.api.crm8.dynamics.com/api/data/v9.1/WhoAmI",
HttpCompletionOption.ResponseHeadersRead).Result;
if (response.IsSuccessStatusCode)
{
//Get the response content and parse it.
JObject body = JObject.Parse(response.Content.ReadAsStringAsync().Result);
Guid userId = (Guid)body["UserId"];
Console.WriteLine("Your system user ID is: {0}", userId);
}
else
{
throw new Exception(response.ReasonPhrase);
}
}
}
catch (Exception ex)
{
DisplayException(ex);
}
}
/// <summary> Displays exception information to the console. </summary>
/// <param name="ex">The exception to output</param>
private static void DisplayException(Exception ex)
{
Console.WriteLine("The application terminated with an error.");
Console.WriteLine(ex.Message);
while (ex.InnerException != null)
{
Console.WriteLine("\t* {0}", ex.InnerException.Message);
ex = ex.InnerException;
}
}
}
class OAuthMessageHandler : DelegatingHandler
{
private UserPasswordCredential _credential;
private AuthenticationContext _authContext = new AuthenticationContext("login.microsoftonline.com/common", false);
private string _clientId;
private string _serviceUrl;
public OAuthMessageHandler(string serviceUrl, string clientId, string userName, string password,
HttpMessageHandler innerHandler)
: base(innerHandler)
{
_credential = new UserPasswordCredential(userName, password);
_clientId = clientId;
_serviceUrl = serviceUrl;
}
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
try
{
AuthenticationResult result = null;
result = await _authContext.AcquireTokenAsync(_serviceUrl, _clientId, _credential);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
// new AuthenticationHeaderValue("Bearer", _authContext.(_serviceUrl, _clientId, _credential).AccessToken);
return await base.SendAsync(request, cancellationToken);
}
catch (Exception ex)
{
throw ex;
}
}
}
}
Please Mark by answer verified if it is helpful.