ssl 如何在.NET Core HttpClient中允许所有https而不管其有效性?

mlnl4t2r  于 2023-10-19  发布在  .NET
关注(0)|答案(5)|浏览(136)

我正在.NET Core中创建一个Web API。为了在本地调试它,我创建了一个连接到我的API的控制台应用程序。我正在Linux中调试。
当连接到https://localhost:5001/上的本地URL时,控制台应用程序抛出AuthenticationException(根据验证过程,远程证书无效)。
我试着用两种方法来规避这一点:
1.已经添加了ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;,但没有效果。
1.运行dotnet dev-certs https --trust。现在我的Web浏览器不再抱怨了,这很好,但是我的控制台应用程序仍然抛出异常。尝试重新启动。
如何让.NET Core信任我的本地主机服务器?还是忽略证书有效期?

esbemjvw

esbemjvw1#

从这里使用下面的示例

var httpClientHandler = new HttpClientHandler();
// Return `true` to allow certificates that are untrusted/invalid
httpClientHandler.ServerCertificateCustomValidationCallback = 
    HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
var httpClient = new HttpClient(httpClientHandler);
njthzxwz

njthzxwz2#

我找到了解决办法:

var httpClientHandler = new HttpClientHandler();

httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true; // DEBUGGING ONLY

var httpClient = new HttpClient(httpClientHandler);

尽管我仍然不清楚为什么在运行dotnet dev-certs https --trust后证书不被认为是有效的。

j91ykkif

j91ykkif3#

对于.NET Core 7.0:
在Web App项目的program.cs类中添加AddHttpClient()方法时:

builder.Services.AddHttpClient("HttpClientName", c =>{}).ConfigurePrimaryHttpMessageHandler(() =>
      {
          var handler = new HttpClientHandler();
          handler.ServerCertificateCustomValidationCallback =
          HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
          return handler;
      });
gg0vcinb

gg0vcinb4#

定义这些函数:

public static void IgnoreBadCertificates()
{
    System.Net.ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
}

private static bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
    return true;
}

然后像这样使用程序的顶部:

IgnoreBadCertificates();
dw1jzc5e

dw1jzc5e5#

您应该通过将证书导入到证书存储区来信任计算机上的证书。
禁用验证是一个坏主意,因为您可能忘记删除该代码,然后您的成品是不安全的

相关问题