.net core中Grpc使用报错:The remote certificate is invalid according to the validation procedure.

yizhihongxing

因为Grpc采用HTTP/2作为通信协议,默认采用LTS/SSL加密方式传输,比如使用.net core启动一个服务端(被调用方)时:  

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.ConfigureKestrel(options =>
                {
                    options.ListenAnyIP(5000, listenOptions =>
                    {
                        listenOptions.Protocols = HttpProtocols.Http2;
                        listenOptions.UseHttps("xxxxx.pfx", "password");
                    });
                });
                webBuilder.UseStartup<Startup>();
            });

 

  其中使用UseHttps方法添加证书和秘钥。

  但是,有时候,比如开发阶段,我们可能没有证书,或者是一个自己制作的临时测试证书,那么在客户端(调用方)调用是可能就会出现下面的异常:  

  Call failed with gRPC error status. Status code: 'Internal', Message: 'Error starting gRPC call. HttpRequestException: The SSL connection could not be established, see inner exception. AuthenticationException: The remote certificate is invalid according to the validation procedure.'.
  fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
   An unhandled exception has occurred while executing the request.
  Grpc.Core.RpcException: Status(StatusCode="Internal", Detail="Error starting gRPC call. HttpRequestException: The SSL connection could not be established, see inner exception. AuthenticationException: The remote certificate is invalid according to the validation procedure.", DebugException="System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception.
  ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.
   at System.Net.Security.SslStream.StartSendAuthResetSignal(ProtocolToken message, AsyncProtocolRequest asyncRequest, ExceptionDispatchInfo exception)
   at System.Net.Security.SslStream.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslStream.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslStream.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslStream.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslStream.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslStream.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslStream.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslStream.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslStream.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslStream.PartialFrameCallback(AsyncProtocolRequest asyncRequest)
    --- End of stack trace from previous location where exception was thrown ---
   at System.Net.Security.SslStream.ThrowIfExceptional()
   at System.Net.Security.SslStream.InternalEndProcessAuthentication(LazyAsyncResult lazyResult)
   at System.Net.Security.SslStream.EndProcessAuthentication(IAsyncResult result)
   at System.Net.Security.SslStream.EndAuthenticateAsClient(IAsyncResult asyncResult)
  ..........

   然而我们可能没有办法得到有效的证书,这时,我们有两个办法:

  1、使用http协议

  想想,我们为什么要使用Grpc?因为高性能,高效率,简单易用吧,但是https相比http就是多个加密的过程,这可能会有一定的性能损失(一般可忽略)。

  而一般的,我们在微服务架构中使用Grpc比较多,而微服务一般部署在我们自己的一个子网下,这也就没必要使用https了吧?

     首先我们知道,Grpc是基于HTTP/2作为通信协议的,而HTTP/2默认是基于LTS/SSL加密技术的,或者说默认需要https协议支持(https=http+lts/ssl),而HTTP/2又支持明文传输,即对http也是支持,但是一般需要我们自己去设置。

  当我们使用Grpc时,又不去改变这个默认行为,那可能就会导致上面的报错。

  在.net core开发中,Grpc要支持http,我们需要显示的指定不需要TLS支持,官方给出的做法是添加如下配置(比如客户端(调用方在ConfigureServices添加):  

    public void ConfigureServices(IServiceCollection services)
    {
        //显式的指定HTTP/2不需要TLS支持
        AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); 
        AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2Support", true);

        services.AddGrpcClient<Greeter.GreeterClient>(nameof(Greeter.GreeterClient), options =>
        {
            options.Address = new Uri("http://localhost:5000");
        });

        ...
    }

  2、调用时不对证书进行验证

  如果是控制台程序,我们可以这么做:  

    public static void Main(string[] args)
    {
        var channel = GrpcChannel.ForAddress("https://localhost:5000", new GrpcChannelOptions()
        {
            HttpClient = null,
            HttpHandler = new HttpClientHandler
            {
                //方法一
                ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
                //方法二
                //ServerCertificateCustomValidationCallback = (a, b, c, d) => true
            }
        });

        var client = new Greeter.GreeterClient(channel);
        var result = client.SayHello(new HelloRequest() { Name = "Grpc" });
    }

 

  其中 HttpClientHandler 的 ServerCertificateCustomValidationCallback 是对证书的自定义验证,上面给出了两种方式验证。

  如果是.net core的webmvc或者webapi程序,因为.net core 3.x开始已经支持了Grpc的引入,所以我只需要在ConfigureServices中注入Grpc的客户端是进行设置:  

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddGrpcClient<Greeter.GreeterClient>(nameof(Greeter.GreeterClient), options =>
        {
            options.Address = new Uri("https://localhost:5000");
        }).ConfigurePrimaryHttpMessageHandler(() =>
        {
            return new HttpClientHandler
            {
                //方法一
                ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
                //方法二
                //ServerCertificateCustomValidationCallback = (a, b, c, d) => true
            };
        });

        ...
    }

  因为.net core3.x中Grpc的使用是基于它的HttpClient机制,比如 AddGrpcClient 方法返回的就是一个 IHttpClientBuilder 接口对象,上面的配置我们还可以这么写:  

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddGrpcClient<Greeter.GreeterClient>(nameof(Greeter.GreeterClient));
        services.AddHttpClient(nameof(Greeter.GreeterClient), httpClient =>
        {
            httpClient.BaseAddress = new Uri("https://localhost:5000");
        }).ConfigurePrimaryHttpMessageHandler(() =>
        {
            return new HttpClientHandler
            {
                //方法一
                ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
                //方法二
                //ServerCertificateCustomValidationCallback = (a, b, c, d) => true
            };
        });

        ...
    }

  总之,不管怎么调用,机制都是一样的,最终都是像上面的客户端调用一样去创建Client,只要能理解就好了。

原文链接:https://www.cnblogs.com/chenyishi/p/17312313.html

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:.net core中Grpc使用报错:The remote certificate is invalid according to the validation procedure. - Python技术站

(1)
上一篇 2023年4月19日
下一篇 2023年4月19日

相关文章

  • C#中把日志导出到txt文本的简单实例

    C#中把日志导出到txt文本的简单实例,可以分为以下几步: 1. 引入System.IO命名空间 首先,在程序的顶部引入System.IO命名空间,即: using System.IO; 2. 创建txt文件,并写入日志内容 接着,在程序中创建txt文件,并将日志内容写入该文件中。下面是一个示例: string logFilePath = @"D:…

    C# 2023年6月1日
    00
  • c# 图片加密解密的实例代码

    c# 图片加密解密是一种通过对图片进行加密操作来保障图片内容安全的方法。下面我们将提供一份完整的攻略,介绍如何使用c#实现图片加密解密。 准备工作 在开始之前,我们需要先下载并安装c#运行环境,常用的c#开发环境有Visual Studio和Visual Studio Code。本攻略将使用Visual Studio 2019作为开发环境。 实现过程 图片加…

    C# 2023年6月8日
    00
  • ASP.NET 2.0,C#—-图像特效处理

    ASP.NET 2.0 是一个使用 Microsoft .NET Framework 构建 Web 应用程序的开发平台,它可以通过 .NET Framework 提供的底层支持来操作和管理一些基础设施,其中包括图像特效处理。本攻略将围绕着 ASP.NET 2.0 和 C#,详细讲解图像特效处理。 创建 ASP.NET 2.0 项目 首先,在 Visual S…

    C# 2023年6月3日
    00
  • 总结十条.NET异常处理建议

    下面我将对如何总结十条.NET异常处理建议进行详细讲解。在.NET应用程序中,正确处理异常异常是保证应用程序稳定性和可靠性的关键,可以避免应用程序出现崩溃和数据丢失等问题。因此,我们需要总结出一些通用的.NET异常处理建议。 1. 记录异常日志 在捕捉异常后,我们需要记录异常日志来帮助我们更快地找到问题。记录异常日志的方式有很多,例如使用log4net和NL…

    C# 2023年5月15日
    00
  • IdentityServer4 QuckStart 授权与自定义Claims的问题

    下面我会详细讲解 IdentityServer4 QuckStart 授权与自定义Claims 的问题,并提供两条示例说明。 什么是 IdentityServer4 QuckStart? IdentityServer4 是一款基于 ASP.NET Core 的开源身份验证和授权服务器。通过 IdentityServer4,我们可以为我们的应用程序提供安全保护…

    C# 2023年6月3日
    00
  • C#中的Lazy如何使用详解

    C#中的Lazy如何使用详解 在C#中,我们经常会遇到需要延迟加载的情况,例如需要从数据库中加载数据,或者需要进行复杂的计算。此时,我们可以使用Lazy类实现延迟加载。本篇文章将详细介绍如何使用Lazy类。 什么是Lazy Lazy是一个泛型类,可以用于在需要时延迟创建对象或计算结果。Lazy的Value属性用于获取Lazy实例所表示的值。当第一次调用Val…

    C# 2023年6月1日
    00
  • C# 6.0 内插字符串(Interpolated Strings )的使用方法

    当我们需要将表达式嵌入到字符串中时,常规做法是使用字符串拼接。C# 6.0 为我们提供了内插字符串(Interpolated Strings)功能,使得我们可以更方便地将表达式嵌入到字符串中。本文将详细介绍内插字符串的使用方法。 什么是内插字符串? 在 C# 6.0 中,内插字符串是一种新的字符串语法,它允许将变量值或表达式嵌入到字符串中。内插字符串使用 $…

    C# 2023年6月3日
    00
  • .Net Core实现健康检查的示例代码

    .NET Core实现健康检查的示例代码 在.NET Core中,可以使用健康检查来监视应用程序的状态并检测故障。本攻略将介绍如何在.NET Core中实现健康检查,并提供两个示例说明。 步骤一:安装Microsoft.AspNetCore.Diagnostics.HealthChecks包 在.NET Core中,可以使用Microsoft.AspNetC…

    C# 2023年5月16日
    00
合作推广
合作推广
分享本页
返回顶部