Ram*_*ppy 67 c# ssl ssl-certificate asp.net-core
我正在开发一个需要连接到https站点的项目.每次连接时,我的代码都会抛出异常,因为该站点的证书来自不受信任的站点.有没有办法绕过证书检查.net核心http?
我在以前版本的.NET中看到了这段代码.我想我只需要这样的东西.
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
Run Code Online (Sandbox Code Playgroud)
kda*_*eid 101
您可以使用这样的匿名回调函数覆盖HTTP调用的SSL证书检查
handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
Run Code Online (Sandbox Code Playgroud)
另外,我建议使用工厂模式,PlatformNotSupportedException因为它是一个可能不会立即处理的共享对象,因此连接将保持打开状态.
Set*_*Set 23
.Net Core不支持ServicePointManager.ServerCertificateValidationCallback.
目前的情况是,它将成为 即将推出的4.1.*System.Net.Http合同(HttpClient)的新ServerCertificateCustomValidationCallback方法..NET Core团队现在正在最终确定4.1合同.你可以在github上看到这个
您可以直接在CoreFx或MYGET Feed中使用源代码来试用System.Net.Http 4.1的预发布版本:https://dotnet.myget.org/gallery/dotnet-core
Github上的当前WinHttpHandler.ServerCertificateCustomValidationCallback定义
Tro*_*sen 23
来到这里寻找同一问题的答案,但我正在使用WCF for NET Core.如果你在同一条船上,请使用:
client.ClientCredentials.ServiceCertificate.SslCertificateAuthentication =
new X509ServiceCertificateAuthentication()
{
CertificateValidationMode = X509CertificateValidationMode.None,
RevocationMode = X509RevocationMode.NoCheck
};
Run Code Online (Sandbox Code Playgroud)
Sam*_*meh 17
在 .NetCore 中,您可以在 services configure 方法中添加以下代码片段,我添加了一个检查以确保我们仅在开发环境中通过 SSL 证书
services.AddHttpClient("HttpClientName", client => {
// code to configure headers etc..
}).ConfigurePrimaryHttpMessageHandler(() => {
var handler = new HttpClientHandler();
if (hostingEnvironment.IsDevelopment())
{
handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; };
}
return handler;
});
Run Code Online (Sandbox Code Playgroud)
小智 14
我用这个解决:
启动文件
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpClient("HttpClientWithSSLUntrusted").ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
{
ClientCertificateOptions = ClientCertificateOption.Manual,
ServerCertificateCustomValidationCallback =
(httpRequestMessage, cert, cetChain, policyErrors) =>
{
return true;
}
});
Run Code Online (Sandbox Code Playgroud)
YourService.cs
public UserService(IHttpClientFactory clientFactory, IOptions<AppSettings> appSettings)
{
_appSettings = appSettings.Value;
_clientFactory = clientFactory;
}
var request = new HttpRequestMessage(...
var client = _clientFactory.CreateClient("HttpClientWithSSLUntrusted");
HttpResponseMessage response = await client.SendAsync(request);
Run Code Online (Sandbox Code Playgroud)
小智 10
在 .NET Core 2.2 和 Docker Linux 容器上使用自签名证书和客户端证书身份验证时,我遇到了同样的问题。在我的开发 Windows 机器上一切正常,但在 Docker 中我得到了这样的错误:
System.Security.Authentication.AuthenticationException: 根据验证程序,远程证书无效
幸运的是,证书是使用链生成的。当然,您可以随时忽略此解决方案并使用上述解决方案。
所以这是我的解决方案:
我在计算机上使用 Chrome 以P7B格式保存了证书。
使用以下命令将证书转换为 PEM 格式:
openssl pkcs7 -inform DER -outform PEM -in <cert>.p7b -print_certs > ca_bundle.crt
打开 ca_bundle.crt 文件并删除所有主题录音,留下一个干净的文件。下面的例子:
-----BEGIN CERTIFICATE-----
_BASE64 DATA_
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
_BASE64 DATA_
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
_BASE64 DATA_
-----END CERTIFICATE-----
Run Code Online (Sandbox Code Playgroud)
# Update system and install curl and ca-certificates
RUN apt-get update && apt-get install -y curl && apt-get install -y ca-certificates
# Copy your bundle file to the system trusted storage
COPY ./ca_bundle.crt /usr/local/share/ca-certificates/ca_bundle.crt
# During docker build, after this line you will get such output: 1 added, 0 removed; done.
RUN update-ca-certificates
Run Code Online (Sandbox Code Playgroud)
var address = new EndpointAddress("https://serviceUrl");
var binding = new BasicHttpsBinding
{
CloseTimeout = new TimeSpan(0, 1, 0),
OpenTimeout = new TimeSpan(0, 1, 0),
ReceiveTimeout = new TimeSpan(0, 1, 0),
SendTimeout = new TimeSpan(0, 1, 0),
MaxBufferPoolSize = 524288,
MaxBufferSize = 65536,
MaxReceivedMessageSize = 65536,
TextEncoding = Encoding.UTF8,
TransferMode = TransferMode.Buffered,
UseDefaultWebProxy = true,
AllowCookies = false,
BypassProxyOnLocal = false,
ReaderQuotas = XmlDictionaryReaderQuotas.Max,
Security =
{
Mode = BasicHttpsSecurityMode.Transport,
Transport = new HttpTransportSecurity
{
ClientCredentialType = HttpClientCredentialType.Certificate,
ProxyCredentialType = HttpProxyCredentialType.None
}
}
};
var client = new MyWSClient(binding, address);
client.ClientCredentials.ClientCertificate.Certificate = GetClientCertificate("clientCert.pfx", "passwordForClientCert");
// Client certs must be installed
client.ClientCredentials.ServiceCertificate.SslCertificateAuthentication = new X509ServiceCertificateAuthentication
{
CertificateValidationMode = X509CertificateValidationMode.ChainTrust,
TrustedStoreLocation = StoreLocation.LocalMachine,
RevocationMode = X509RevocationMode.NoCheck
};
Run Code Online (Sandbox Code Playgroud)
GetClientCertificate 方法:
private static X509Certificate2 GetClientCertificate(string clientCertName, string password)
{
//Create X509Certificate2 object from .pfx file
byte[] rawData = null;
using (var f = new FileStream(Path.Combine(AppContext.BaseDirectory, clientCertName), FileMode.Open, FileAccess.Read))
{
var size = (int)f.Length;
var rawData = new byte[size];
f.Read(rawData, 0, size);
f.Close();
}
return new X509Certificate2(rawData, password);
}
Run Code Online (Sandbox Code Playgroud)
允许所有证书非常强大,但也可能很危险。如果您只想允许有效的证书加上某些特定的证书,可以这样做。
using (var httpClientHandler = new HttpClientHandler())
{
httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, sslPolicyErrors) => {
if (sslPolicyErrors == SslPolicyErrors.None)
{
return true; //Is valid
}
if (cert.GetCertHashString() == "99E92D8447AEF30483B1D7527812C9B7B3A915A7")
{
return true;
}
return false;
};
using (var httpClient = new HttpClient(httpClientHandler))
{
var httpResponse = httpClient.GetAsync("https://example.com").Result;
}
}
Run Code Online (Sandbox Code Playgroud)
原始来源:
首先,不要在生产中使用它
如果您使用 AddHttpClient 中间件,这将很有用。我认为它是用于开发目的而不是生产目的。在您创建有效证书之前,您可以使用此功能。
Func<HttpMessageHandler> configureHandler = () =>
{
var bypassCertValidation = Configuration.GetValue<bool>("BypassRemoteCertificateValidation");
var handler = new HttpClientHandler();
//!DO NOT DO IT IN PRODUCTION!! GO AND CREATE VALID CERTIFICATE!
if (bypassCertValidation)
{
handler.ServerCertificateCustomValidationCallback = (httpRequestMessage, x509Certificate2, x509Chain, sslPolicyErrors) =>
{
return true;
};
}
return handler;
};
Run Code Online (Sandbox Code Playgroud)
并应用它
services.AddHttpClient<IMyClient, MyClient>(x => { x.BaseAddress = new Uri("https://localhost:5005"); })
.ConfigurePrimaryHttpMessageHandler(configureHandler);
Run Code Online (Sandbox Code Playgroud)
对于 .NET 6,您可以像这样配置主要 Http 消息处理程序:
services.AddHttpClient<ITodoListService, TodoListService>()
.ConfigurePrimaryHttpMessageHandler(() => {
var handler = new HttpClientHandler();
if (currentEnvironment.IsDevelopment()) {
handler.ServerCertificateCustomValidationCallback =
HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
}
return handler;
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
47814 次 |
| 最近记录: |