Search code examples
c#asp.net-coregrpc

how to use ssl certificates with gRPC and ASP Net Core 3.0?


I am rtying to configure the service to use a SSL certificate. I have read this post:

How to enable server side SSL for gRPC?

I guess this is the main code:

var cacert = File.ReadAllText(@"ca.crt");
var servercert = File.ReadAllText(@"server.crt");
var serverkey = File.ReadAllText(@"server.key");
var keypair = new KeyCertificatePair(servercert, serverkey);
var sslCredentials = new SslServerCredentials(new List<KeyCertificatePair>() { keypair }, cacert, false);

var server = new Server
{
    Services = { GrpcTest.BindService(new GrpcTestImpl(writeToDisk)) },
    Ports = { new ServerPort("0.0.0.0", 555, sslCredentials) }
};
server.Start();

The problem is that in my case, I don't start the service in this way, I am using kestrel, and the code is this:

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.ConfigureKestrel(options =>
            {
                System.Net.IPAddress miAddress = System.Net.IPAddress.Parse("x.x.x.x");
                //options.Listen(miAddress, 5001, o => o.Protocols = HttpProtocols.Http2);

                options.Listen(miAddress, 5001, l =>
                {
                    l.Protocols = HttpProtocols.Http2;
                    l.UseHttps();
                    });
            });
            webBuilder.UseStartup<Startup>();
        });

In this case, I don't have access to SslCredentials, so I can't create a new one.

How could I configure my ssl certificate using kestrel?

Thanks.


Solution

  • The post you linked to is for Grpc.Core, the grpc-dotnet implementation is configured differently.

    This documentation and example should help: https://github.com/grpc/grpc-dotnet/blob/dd72d6a38ab2984fd224aa8ed53686dc0153b9da/testassets/InteropTestsWebsite/Program.cs#L55

    https://learn.microsoft.com/en-us/aspnet/core/grpc/authn-and-authz?view=aspnetcore-3.1

    (in another words, you can configure the certificates on the server side exactly the same way as you would for any other HTTP/2 server - there's nothing grpc specific in configuring the secure connections in ASP.NET Core).