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

chester·chen發表於2023-04-13

因為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,只要能理解就好了。

相關文章