如何解决c# gRPC Context.Connection.ClientCertificate 在服务器端始终为空
我有一个托管在 .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);
怎么了?
谢谢
解决方法
问题与证书本身有关。我忘了添加客户端身份验证扩展。奇怪的是,如果我将它与 grpcui 一起使用,它可以正常工作。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。