是否可以在 Grpc.Core 中接受自签名证书?

Geo*_*org 5 .net c# ssl grpc

场景:我有一个用 C# 实现的客户端,它应该使用 gRPC 连接到服务器,使用 SSL 进行加密连接。但是,服务器使用的证书可能是自签名的,也可能不是。

在文档中,我只看到我可以通过使用自定义根证书(或使用不会验证自签名证书的公共根 CA)来设置不安全(根本没有 SSL)或安全的通道凭据,这实际上意味着我必须确保以 root 身份安装自签名服务器证书。基本上,我如何以编程方式做到这一点?

var channelCredentials = new SslCredentials(rootAsPem); 
// FIXME: specify that channelCredentials can accept self-signed certificates or fetch certificates?
var channel = new Channel("myservice.example.com", channelCredentials);
var client = new Greeter.GreeterClient(channel);
Run Code Online (Sandbox Code Playgroud)

我想实现的是询问用户“嘿,您配置的服务器使用自签名证书,您同意吗?” 如果是,请将证书安装为 PEM 中的根证书。

我现在的主要问题是:

  1. 我什至如何获得服务器证书?我目前得到的只是一个例外。
  2. 是否可以避免将服务器证书安装为根证书?

小智 8

var httpClientHandler = new HttpClientHandler();
// Return `true` to allow certificates that are untrusted/invalid
httpClientHandler.ServerCertificateCustomValidationCallback = 
    HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
var httpClient = new HttpClient(httpClientHandler);
var channel = GrpcChannel.ForAddress("https://localhost:5001",
    new GrpcChannelOptions { HttpClient = httpClient });
var client = new Greet.GreeterClient(channel);
Run Code Online (Sandbox Code Playgroud)

https://docs.microsoft.com/en-us/aspnet/core/grpc/troubleshoot?view=aspnetcore-3.0


Geo*_*org 1

对于那些有同样问题的人:不幸的是,目前这是不可能的。C 库确实允许这样做,但 C# 包装器不允许。有一个拉取请求正在进行中,但尚未合并:https ://github.com/grpc/grpc/pull/17051