yogihosting
yogihosting

Reputation: 6332

Client Certificate received null in gRPC implemented in C# Console App

I am implementing a simple gRPC project in C# as listed in official docs. It is very simple and have 2 projects:

  1. gRPC service - containing the gRPC service
  2. C# console app - that calls the gRPC service

The gRPC service method called code is given below:

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
    });
}

Notice I am trying to read the client certificate as:

var httpContext = context.GetHttpContext();

var clientCertificate = httpContext.Connection.ClientCertificate;

The problem is that I receive null for client certificate. I checked it by putting breakpoint in Visual Studio. Why it is so ?

The C# console apps which calls this gRPC service is:

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);
}

Here I am adding the certificate in code lines:

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

var handler = new HttpClientHandler();

handler.ClientCertificates.Add(cert);

Why is the certificate received null?

Upvotes: 1

Views: 785

Answers (1)

yogihosting
yogihosting

Reputation: 6332

I found the answer after doing a lot of research and hope it helps others too. In the gRPC service project, go to CreateHostBuilder() function of the Program.cs and configure Kestrel to require client certificate. The below code lines are the ones doing this work:

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);
                });
            });

Upvotes: 0

Related Questions