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

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章