asp.net core 配置证书身份验证

让服务器配置为可以接受客户端证书的方法    

Microsoft.AspNetCore.Authentication.Certificate

 

            services.AddAuthentication(CertificateAuthenticationDefaults.AuthenticationScheme)
            .AddCertificate()
            .AddCertificateCache();

 

生成证书请看

https://www.cnblogs.com/buchizaodian/p/15483758.html

 

Kestrel服务端配置证书

服务端

 GrpcService1 是项目名称,crypticpassword是密码

    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }
        public static IHostBuilder CreateHostBuilder(string[] args) =>
                    Host.CreateDefaultBuilder(args)
                        .ConfigureWebHostDefaults(webBuilder =>
                        {
                            webBuilder.UseKestrel(option =>
                            {
                                option.ConfigureHttpsDefaults(i =>
                                {
                                    i.ServerCertificate = new System.Security.Cryptography.X509Certificates.X509Certificate2("./GrpcService1.pfx", "crypticpassword");
                                });
                            }).UseStartup<Startup>().UseUrls("http://*:5000;https://*:5001");
                        });
    }

 报这个错误是因为证书不受信任

 

IIS服务端配置证书

 

自定义 web 代理中使用证书身份验证 

如nginx

 

客户端使用证书+grpc

            var cert = new X509Certificate2("./GrpcService1.pfx", "crypticpassword");
            var handler = new HttpClientHandler();
            handler.ClientCertificates.Add(cert);
            //来允许在没有受信任证书的情况下进行调用
            handler.ServerCertificateCustomValidationCallback =HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
            var channel = GrpcChannel.ForAddress("https://127.0.0.1:5001", new GrpcChannelOptions
            {
                HttpHandler = handler
            });
            var client = new Greeter.GreeterClient(channel);
            HelloRequest helloRequest = new HelloRequest();
            helloRequest.Name = "Tom";

            HelloReply helloReply = new HelloReply();

            Random random = new Random();
            while (true)
            {
                Thread.Sleep(1000);

                helloRequest.Name = random.Next().ToString();
                helloReply = client.SayHello(helloRequest);
            }

 

 

posted @ 2021-10-29 16:37  富坚老贼  阅读(688)  评论(0编辑  收藏  举报