因為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了吧?
具體可參考我上一篇:.net core中Grpc使用報錯:The response ended prematurely.
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,只要能理解就好了。