因?yàn)镚rpc采用HTTP/2作為通信協(xié)議,默認(rèn)采用LTS/SSL加密方式傳輸,比如使用.net core啟動(dòng)一個(gè)服務(wù)端(被調(diào)用方)時(shí):
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方法添加證書和秘鑰。
但是,有時(shí)候,比如開發(fā)階段,我們可能沒有證書,或者是一個(gè)自己制作的臨時(shí)測(cè)試證書,那么在客戶端(調(diào)用方)調(diào)用是可能就會(huì)出現(xiàn)下面的異常:
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) ..........
? 然而我們可能沒有辦法得到有效的證書,這時(shí),我們有兩個(gè)辦法:
1、使用http協(xié)議
想想,我們?yōu)槭裁匆褂肎rpc?因?yàn)楦咝阅?,高效率,?jiǎn)單易用吧,但是https相比http就是多個(gè)加密的過程,這可能會(huì)有一定的性能損失(一般可忽略)。
而一般的,我們?cè)谖⒎?wù)架構(gòu)中使用Grpc比較多,而微服務(wù)一般部署在我們自己的一個(gè)子網(wǎng)下,這也就沒必要使用https了吧?
? ? 首先我們知道,Grpc是基于HTTP/2作為通信協(xié)議的,而HTTP/2默認(rèn)是基于LTS/SSL加密技術(shù)的,或者說默認(rèn)需要https協(xié)議支持(https=http+lts/ssl),而HTTP/2又支持明文傳輸,即對(duì)http也是支持,但是一般需要我們自己去設(shè)置。
當(dāng)我們使用Grpc時(shí),又不去改變這個(gè)默認(rèn)行為,那可能就會(huì)導(dǎo)致上面的報(bào)錯(cuò)。
在.net core開發(fā)中,Grpc要支持http,我們需要顯示的指定不需要TLS支持,官方給出的做法是添加如下配置(比如客戶端(調(diào)用方)在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、調(diào)用時(shí)不對(duì)證書進(jìn)行驗(yàn)證
如果是控制臺(tái)程序,我們可以這么做:
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?是對(duì)證書的自定義驗(yàn)證,上面給出了兩種方式驗(yàn)證。
如果是.net core的webmvc或者webapi程序,因?yàn)?net core 3.x開始已經(jīng)支持了Grpc的引入,所以我只需要在ConfigureServices中注入Grpc的客戶端是進(jìn)行設(shè)置:
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 }; }); ... }
因?yàn)?net core3.x中Grpc的使用是基于它的HttpClient機(jī)制,比如 AddGrpcClient 方法返回的就是一個(gè) IHttpClientBuilder 接口對(duì)象,上面的配置我們還可以這么寫: 文章來源:http://www.zghlxwxcb.cn/news/detail-412108.html
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 }; }); ... }
總之,不管怎么調(diào)用,機(jī)制都是一樣的,最終都是像上面的客戶端調(diào)用一樣去創(chuàng)建Client,只要能理解就好了。文章來源地址http://www.zghlxwxcb.cn/news/detail-412108.html
到了這里,關(guān)于.net core中Grpc使用報(bào)錯(cuò):The remote certificate is invalid according to the validation procedure.的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!