Having a hard time converting a successful Postman request to a successful request in C#. Showing my code using HttpClient, but have also tried with PostSharp and HttpRequest. I am using a local pfx certificate file which has a password.
In Postman:
- Added the PFX cert to Client Certificates
- Authorization tab has username and password (Basic Auth)
- Authorization header automatically generates based on above ("Basic <encoded username/password>")
- Body is "{}"
Sends successfully (200).
Using HttpClient:
var host = @"https://thehost/service/verb?param1=blah¶m2=1111111";
const string certName = @"C:\Key.pfx";
const string userName = "userName";
const string certPassword = "password1";
const string authPassword = "password2";
var handler = new HttpClientHandler();
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
// tried many combinations here
handler.SslProtocols = SslProtocols.Tls | SslProtocols.Tls11 |
SslProtocols.Tls12 | SslProtocols.Tls13;
var cert = new X509Certificate2(certName, certPassword);
handler.ClientCertificates.Add(cert);
//not sure if this is needed
handler.ServerCertificateCustomValidationCallback += (message, certificate2, arg3, arg4) => true;
var client = new HttpClient(handler);
//not sure if these are needed
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.ConnectionClose = true;
// added this to both the request and the client.
// Also tried "*/*" for both
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var request = new HttpRequestMessage();
request.RequestUri = new Uri(host);
request.Headers.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
request.Content = new StringContent("{}", Encoding.UTF8,
"application/json");
request.Method = HttpMethod.Post;
//basic auth header
var authenticationString = $"{userName}:{authPassword}";
var base64EncodedAuthenticationString = Convert.ToBase64String(Encoding.UTF8.GetBytes(authenticationString));
var authHeader = new AuthenticationHeaderValue("Basic",
base64EncodedAuthenticationString);
request.Headers.Authorization = authHeader;
try
{
var httpResponseMessage = client.SendAsync(request).ConfigureAwait(false).GetAwaiter().GetResult();
}catch (Exception e){
Console.WriteLine(e);
throw;
}
This returns Unauthorized (401). The response text contains "Invalid user name or password."
Any thoughts on what might not be matching up between the two requests?