繁体   English   中英

在 C# 控制台应用程序中实现的 gRPC 中收到的客户端证书 null

[英]Client Certificate received null in gRPC implemented in C# Console App

我在官方文档中列出的 C# 中实现了一个简单的 gRPC 项目。 它非常简单,有 2 个项目:

  1. gRPC 服务 - 包含 gRPC 服务
  2. C# 控制台应用程序 - 调用 gRPC 服务

gRPC服务方法调用代码如下:

public override Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context)
{
    var httpContext = context.GetHttpContext();
    var clientCertificate = httpContext.Connection.ClientCertificate;

    return Task.FromResult(new HelloReply
    {
        Message = "Hello " + request.Name
    });
}

请注意,我正在尝试将客户端证书读取为:

var httpContext = context.GetHttpContext();

var clientCertificate = httpContext.Connection.ClientCertificate;

问题是我收到 null 用于客户端证书。 我通过在 Visual Studio 中放置断点来检查它。 为什么会这样?

调用此 gRPC 服务的 C# 控制台应用程序是:

static async Task Main(string[] args)
{
    // The port number(5001) must match the port of the gRPC server.
    var basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location);
    var cert = new X509Certificate2(Path.Combine(basePath, "client.pfx"), "1234");
    var handler = new HttpClientHandler();
    handler.ClientCertificates.Add(cert);
    var httpClient = new HttpClient(handler);

    var channel = GrpcChannel.ForAddress("https://localhost:5001/", new GrpcChannelOptions
    {
        HttpClient = httpClient
    });
    var grpc = new Greeter.GreeterClient(channel);
    var response = await grpc.SayHelloAsync(new HelloRequest { Name = "Bob" });
    Console.WriteLine(response.Message);
}

在这里,我在代码行中添加证书:

var cert = new X509Certificate2(Path.Combine(basePath, "client.pfx"), "1234");

var handler = new HttpClientHandler();

handler.ClientCertificates.Add(cert);

为什么收到的证书是 null?

经过大量研究后,我找到了答案,并希望对其他人也有帮助。 在 gRPC 服务项目中,go 到Program.csCreateHostBuilder() function 并配置 Kestrel 要求客户端证书 以下代码行是执行此工作的代码行:

public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
                //configure to require client certificate
                webBuilder.ConfigureKestrel(o =>
                {
                    o.ConfigureHttpsDefaults(o =>
                        o.ClientCertificateMode = ClientCertificateMode.RequireCertificate);
                });
            });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM