簡體   English   中英

c# gRPC Context.Connection.ClientCertificate 在服務器端始終為 null

[英]c# gRPC Context.Connection.ClientCertificate is always null on server side

我有一個托管在 .NET 5 Web 項目上的 gRPC 服務,我從另一個 .NET 5 Z2567A5EC3705EB7AC2CCE8Z 項目調用該項目我需要使用證書保護通道,使用 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 始終是 null:

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一起使用,它可以正常工作。

暫無
暫無

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

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