首页 > 解决方案 > grpc客户端的证书认证问题

问题描述

我创建了一个带有 gRPC 客户端(控制台应用程序)和一个 gRPC 服务器应用程序的演示解决方案。(在 .NET Core 3 上为其提供的模板)

我正在尝试测试两者之间的证书身份验证,但由于某种原因它失败并出现以下错误:

AuthenticationException: The remote certificate is invalid according to the validation procedure."

Program.cs的服务器

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
            webBuilder.ConfigureKestrel(o =>
            {
                o.ConfigureHttpsDefaults(o =>
                {
                    o.ClientCertificateMode = ClientCertificateMode.RequireCertificate;
                    o.ServerCertificate = <MyCertificateWithPrivateKey>;
            });
        });

在客户端应用程序中,我在 HttpHandler 中传递了相同的证书,该证书被传递到我创建的通道,即

GrpcChannel.ForAddress("https://localhost:5001", new GrpcChannelOptions
            {
                HttpHandler = handler
            });

我的服务器的启动类:

 public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddGrpc();
            services.AddAuthentication(CertificateAuthenticationDefaults.AuthenticationScheme)
                .AddCertificate();
        }

        // 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.UseAuthentication();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapGrpcService<GreeterService>();

                endpoints.MapGet("/", async context =>
                {
                    await context.Response.WriteAsync("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");
                });
            });
        }
    }

感谢您能给我的任何帮助。

标签: c#asp.net-core.net-coregrpcclient-certificates

解决方案


推荐阅读