簡體   English   中英

.NET6 和 OpenSSL 上具有 SSL 的 gRPC 服務器

[英]gRPC Server with SSL on .NET6 and OpenSSL

.NET 6 中的 gRPC 服務器部分看起來也不同,現在沒有 Startup.cs,只有 Program.cs 和我通過創建 SERVER ZA2F2ED4F8EBC2CBB4C21A29DC40AB61 的新實例找到的所有示例 go 但是,如果我使用 .NET 6 (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);

但是沒有服務器解決方案。

您仍然可以像以前使用新的“簡化”.NET 6 布局一樣配置 Kestrel,就像這里的 MS Docs中解釋的那樣。 因此,對於您發布的服務器端 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 Docs for console apps 中描述的那樣。 這個Program.cs文件就是一個例子,可以在@Mihal By 在評論中鏈接的 repo 中找到。 如果您 go 回到舊樣式,您也可以像以前一樣為 Kestrel 編寫自己的 Startup.cs。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM