【发布时间】:2021-10-11 22:10:48
【问题描述】:
很难将成功的 Postman 请求转换为 C# 中的成功请求。使用 HttpClient 显示我的代码,但也尝试使用 PostSharp 和 HttpRequest。我正在使用具有密码的本地 pfx 证书文件。
在邮递员中:
• 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 "{}"
发送成功 (200)。
使用 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;
}
这将返回未经授权 (401)。响应文本包含“无效的用户名或密码”。
对于这两个请求之间可能不匹配的问题有什么想法吗?
【问题讨论】:
-
您的请求是否正在重定向?按照设计,这些不会在来自服务器的重定向请求之后发送
-
您可以尝试使用嗅探器(例如,wireshark 或 fiddler)拦截您的请求(和邮递员请求),以查看您是否真的在传输相同的值。不需要设置 SslProtocols 的 AFAIK,只需将该行省略即可。此外,ServerCertificateCustomValidationCallback 应该(对于服务器)产生预期的哈希值。话虽如此;你提到密码应该被编码(“基本”),但不是用户名,尽管你对两者都进行了编码..?
-
确实正如@ESG 所说,重定向将删除所有标头值
-
@ESG 我考虑过重定向——我在 Postman 中关闭了“自动跟踪重定向”,但仍然得到成功响应 (200)。
-
@riffnl 用户名/密码都应该被编码——我将编辑这个问题。不确定您对 ServerCertificateCustomValidationCallback 的意思——您能详细说明一下吗?我将努力在 Fiddler 中捕获这两个请求。
标签: c# postman ssl-certificate dotnet-httpclient