gRPC服务器,在.NET6和OpenSSL上使用SSL



gRPC服务器部分在.NET6中看起来也不一样了,现在没有Startup.cs,只有Program.cs,我找到的所有示例都是通过创建server类的新实例来完成的。但是如果我使用.NET6(Kestrel(,它应该是什么样子呢?

这是";服务器";带有一个.NET 6 Program.cs 服务(MyTestService(的默认代码

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddGrpc();
var app = builder.Build();
// Configure the HTTP request pipeline.
app.MapGrpcService<MyTestService>();
app.MapGet("/", () => "Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909");

这是来自官方gRPC文档的客户端解决方案:

var channelCredentials = new SslCredentials(File.ReadAllText("roots.pem"));  // Load a custom 
roots file.
var channel = new Channel("myservice.example.com", channelCredentials);
var client = new Greeter.GreeterClient(channel);

但是没有服务器解决方案。

更新-gRPC.NET6:的客户端代码

string certificatePem = File.ReadAllText("clientcrt.pem");
string privateKeyPem = File.ReadAllText("clientkey.pem");
var cert = X509Certificate2.CreateFromPem(certificatePem, 
privateKeyPem);
var handler = new HttpClientHandler();
handler.ClientCertificates.Add(cert);
using HttpClient httpClient = new(handler);
var channel = GrpcChannel.ForAddress("https://0.0.0.0:5000", new GrpcChannelOptions
{
HttpClient = httpClient
});
var grpc = new Test.TestClient(channel);

您仍然可以像使用新的";"简化"。NET 6布局,就像这里的MS文档中所解释的那样。因此,对于您发布的服务器端Program.cs,您可以将构建器配置为使用TLS。例如,如果你有一个证书";server_certificate.pfx";对于您发布的默认代码中的服务器,配置生成器如下:

// the code you posted, but with Kestrel configuration
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddGrpc();
// configure the builder to use the TLS certificate
builder.WebHost.ConfigureKestrel(opt =>
{
string file = "server_certificate.pfx";
string password = "P@ssw0rd!";
var cert = new X509Certificate2(file, password);
opt.ConfigureHttpsDefaults(h => {
// Choose RequireCertificate instead of AllowCertificate if it is required
h.ClientCertificateMode = Microsoft.AspNetCore.Server.Kestrel.Https.ClientCertificateMode.AllowCertificate;
// this checks whether the certificate has been signed by some greater authority
h.CheckCertificateRevocation = false;
h.ServerCertificate = cert;
});
});
var app = builder.Build();
// Configure the HTTP request pipeline.
app.MapGrpcService<MyTestService>();
app.MapGet("/", () => "Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909");

另一种选择是对.NET 6中的Program.cs使用旧的.NET 5编程风格(我更喜欢(,就像控制台应用程序的MS文档中描述的那样。这个Program.cs文件就是一个例子,它可以在@Mihal-By在评论中链接的repo中找到。如果你回到旧的风格,你也可以像过去一样为红隼写自己的Startup.cs。

最新更新