我有一个托管在 .NET 5 Web 项目上的 gRPC 服务,我从另一个包含 gRPC 客户端的 .NET 5 Web 项目调用该服务。我需要使用证书保护通道,使用 JWT 令牌保护应用程序,我使用了以下代码:
客户端,gRPC 客户端:
var handler = new HttpClientHandler()
handler.ClientCertificates.Add(ClientCertificate);
var httpClient = new HttpClient(handler);
var callCredentials = CallCredentials.FromInterceptor((context, metadata) =>
{
metadata.Add("Authorization", $"Bearer {token}");
return Task.CompletedTask;
});
var channelCredentials = ChannelCredentials.Create(new SslCredentials(), callCredentials);
using var channel = GrpcChannel.ForAddress("https://localhost:5001", new GrpcChannelOptions()
{
HttpClient = httpClient,
Credentials = channelCredentials
});
var client = new TokenServiceClient(channel);
var response = await client.GetUserTokenAsync(request);
服务器端,Startup.cs:
services.Configure<KestrelServerOptions>(options =>
{
options.ConfigureEndpointDefaults(opt =>
{
opt.Protocols = HttpProtocols.Http2;
});
options.ConfigureHttpsDefaults(opt =>
{
opt.ClientCertificateMode = Microsoft.AspNetCore.Server.Kestrel.Https.ClientCertificateMode.AllowCertificate;
opt.ClientCertificateValidation = (certificate, chain, errors) => certificate.Issuer == ServerCertificate.Issuer;
});
});
我在服务器端还有一个自定义 AuthenticationHandler,如果请求是使用 gRPC 发出的,我在其中检查客户端是否提供了证书,但是属性 Context.Connection.ClientCertificate 始终为空:
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
ClaimsPrincipal principal = null;
try
{
if((Request.ContentType == "application/grpc") && Context.Connection.ClientCertificate == null)
{
return AuthenticateResult.Fail("No certificate provided");
}
//....
}
//....
}
使用以下ClientCertificate
代码从 pfx 文件实例化:
ClientCertificate = new X509Certificate2(certFilePath, certPassword, X509KeyStorageFlags.PersistKeySet);
怎么了?
谢谢