我正在尝试将服务配置为使用 SSL 证书。我读过这篇文章:
我想这是主要代码:
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();
问题是,就我而言,我没有以这种方式启动服务,我使用的是kestrel,代码是这样的:
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>();
});
在这种情况下,我无权访问 SslCredentials,因此无法创建新的。
如何使用 kestrel 配置我的 ssl 证书?
谢谢。
您链接到的帖子适用于 Grpc.Core,grpc-dotnet 实现的配置不同。
https://learn.microsoft.com/en-us/aspnet/core/grpc/authn-and-authz?view=aspnetcore-3.1
(换句话说,您可以按照与任何其他 HTTP/2 服务器完全相同的方式在服务器端配置证书 - 在 ASP.NET Core 中配置安全连接时没有任何 grpc 特定内容)。
您似乎将证书身份验证误认为是 SSL 数据加密。如果您只想加密数据通道,好的做法是使用 Kestrel:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(builder =>
{
builder.ConfigureKestrel(options =>
{
options.Listen(IPAddress.Loopback, 5005, configure => { configure.UseHttps(); configure.Protocols = HttpProtocols.Http2; });
});
});
对 UseHttps() 的调用使用内部 ASP.NET Core 的可信开发证书。
如果您想自己提供一个,请使用 i.e.(或其他重载):
public static ListenOptions UseHttps(this ListenOptions listenOptions, X509Certificate2 serverCertificate)
或在 appsettings.json 中使用以下其中一项:
{
"Kestrel": {
"Endpoints": {
"Http": {
"Url": "http://localhost:5000"
},
"HttpsInlineCertFile": {
"Url": "https://localhost:5001",
"Certificate": {
"Path": "<path to .pfx file>",
"Password": "$CREDENTIAL_PLACEHOLDER$"
}
},
"HttpsInlineCertAndKeyFile": {
"Url": "https://localhost:5002",
"Certificate": {
"Path": "<path to .pem/.crt file>",
"KeyPath": "<path to .key file>",
"Password": "$CREDENTIAL_PLACEHOLDER$"
}
},
"HttpsInlineCertStore": {
"Url": "https://localhost:5003",
"Certificate": {
"Subject": "<subject; required>",
"Store": "<certificate store; required>",
"Location": "<location; defaults to CurrentUser>",
"AllowInvalid": "<true or false; defaults to false>"
}
},
"HttpsDefaultCert": {
"Url": "https://localhost:5004"
}
},
"Certificates": {
"Default": {
"Path": "<path to .pfx file>",
"Password": "$CREDENTIAL_PLACEHOLDER$"
}
}
}
}