gpt4 book ai didi

c# - GRPC 的 SSL 认证

转载 作者:行者123 更新时间:2023-12-05 03:00:22 27 4
gpt4 key购买 nike

你能帮我做 gRPC 服务器的 ssl 认证吗?

这就是我使用 C# 核心控制台应用程序 的方式:

const int Port = 50051;
const string host = "127.0.0.1";

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


var server = new Server()
{
// setup host, port and server credentials
Ports = { new ServerPort(host, Port, sslCredentials) },
// register the service we built earlier
Services = { Messages.BindService(new MessagesImpl()) }
};

server.Start();

我不知道如何在ASP.NET core gRPC Server中提供SslServerCredentials?

cRPG 服务器通过在配置部分的 Stattup.cs 文件中添加来启动:

public void ConfigureServices(IServiceCollection services)
{
services.AddGrpc();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

app.UseRouting();

app.UseEndpoints(endpoints =>
{
// 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
endpoints.MapGrpcService<ServiceBaaseClass>();
});
}

最佳答案

您应该在构建主机时配置 https。如果您使用的是 grpc 模板,那是在 Program.cs 中。

例子:

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.ConfigureKestrel(options =>
{
options.ListenLocalhost(50051, listenOptions =>
{
listenOptions.Protocols = HttpProtocols.Http2;
var cert = new X509Certificate2("localhost.pfx", "test");

listenOptions.UseHttps(cert);
});
});

webBuilder.UseStartup<Startup>();
});

我有一个以这种方式生成的 pfx 文件:

openssl req -new -x509 -newkey rsa:2048 -keyout localhost.key -out localhost.cer -days 365 -subj /CN=localhost
openssl pkcs12 -export -out localhost.pfx -inkey localhost.key -in localhost.cer

关于c# - GRPC 的 SSL 认证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56904639/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com