1

I have a gRPC service hosted on a .NET 5 Web Project which I call from another .NET 5 web Project containing a gRPC client. I need to secure the channel with a certificate and the application with a JWT token and I used this code:

Client-side, gRPC client:

var handler = new HttpClientHandler()
handler.ClientCertificates.Add(ClientCertificate);

var httpClient = new HttpClient(handler);

var callCredentials = CallCredentials.FromInterceptor((context, metadata) =>
{
    metadata.Add("Authorization", $"Bearer {token}");

    return Task.CompletedTask;
});

var channelCredentials = ChannelCredentials.Create(new SslCredentials(), callCredentials);

using var channel = GrpcChannel.ForAddress("https://localhost:5001", new GrpcChannelOptions()
{
    HttpClient = httpClient,
    Credentials = channelCredentials
});

var client = new TokenServiceClient(channel);

var response = await client.GetUserTokenAsync(request);

Server-side, Startup.cs:

services.Configure<KestrelServerOptions>(options =>
{
    options.ConfigureEndpointDefaults(opt =>
    {
        opt.Protocols = HttpProtocols.Http2;
    });
    options.ConfigureHttpsDefaults(opt =>
    {
        opt.ClientCertificateMode = Microsoft.AspNetCore.Server.Kestrel.Https.ClientCertificateMode.AllowCertificate;
        opt.ClientCertificateValidation = (certificate, chain, errors) => certificate.Issuer == ServerCertificate.Issuer;
    });
});

I have also a custom AuthenticationHandler on the server-side, in which I check if the client provided its certificate if the request was made with gRPC, but there the property Context.Connection.ClientCertificate is always null:

protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
    ClaimsPrincipal principal = null;

    try
    {
        if((Request.ContentType == "application/grpc") && Context.Connection.ClientCertificate == null)
        {
            return AuthenticateResult.Fail("No certificate provided");
        }
        //....
    }

    //....
}

The ClientCertificate was instantiated from a pfx file with the following code:

ClientCertificate = new X509Certificate2(certFilePath, certPassword, X509KeyStorageFlags.PersistKeySet);

What's wrong?

Thanks

Giuseppe Terrasi
  • 479
  • 7
  • 22

1 Answers1

0

The problem was related to the certificate itself. I forgot to add to it the Client Authentication extension. The strange thing is that if I use it with grpcui it works correctly.

Giuseppe Terrasi
  • 479
  • 7
  • 22