Search code examples
.netgrpc

How to add certificate credentials in a gRPC channel created with SocketsHttpHandler?


I would like to require the client include the certificate to implement mTLS (mutual authentication).

I have read this documentation: https://learn.microsoft.com/en-us/dotnet/architecture/grpc-for-wcf-developers/channel-credentials

And it explains how I could do it using HttpClientHandler. This is the code:

    var handler = new HttpClientHandler();
    handler.ClientCertificates.Add(cert);
    
    var httpClient = new HttpClient(handler);
    
    var callCredentials = CallCredentials.FromInterceptor(((context, metadata) =>
        {
            metadata.Add("Authorization", $"Bearer {_token}");
        }));
    
    var channelCredentials = ChannelCredentials.Create(new SslCredentials(), callCredentials);
    
    var channel = GrpcChannel.ForAddress("https://localhost:5001/", new GrpcChannelOptions
    {
        HttpClient = httpClient,
        Credentials = channelCredentials
    });

var grpc = new Portfolios.PortfoliosClient(channel);

However, in my case I need to use SocketsHttpHandler to create the channel, because it is needed to can use the client in a MAUI Android application. But it has not the CLientsCertificates collection to can add the certificate.

So how could add my certificate when I need to use the socket?

Thanks.


Solution

  • What about:

    var sslOptions = new SslClientAuthenticationOptions();
    var handler = new SocketsHttpHandler()
    
    
    handler.SslOptions = new SslClientAuthenticationOptions()
    {
        ClientCertificates = new X509CertificateCollection(),
    };
    
    handler.SslOptions.ClientCertificates.Add(yourCertificate);
    

    You might need to further configure your SslOptions and handler but this should cover how to add the certificate