如何在.Net Core中使用客户端SSL证书

时间:2019-01-06 00:31:47

标签: c# .net-core ssl-certificate

我最近想将.net核心网站配置为使用客户端SSL证书身份验证

我找不到很好的例子,所以我做了一些研究,决定将结果发布给其他人。

1 个答案:

答案 0 :(得分:2)

在.net core 2.2中,您可以在.UseHttps中配置Kestrel的同时,在Program.cs方法中将客户端证书配置为选项。

使用此配置,当用户在浏览器中拉出站点时,浏览器将显示一个对话框,要求用户选择用于身份验证的客户端证书。如果证书无效,则服务器将返回HTTP 495 SSL Certificate Error

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .ConfigureKestrel((context, options) =>
            {
                options.Listen(IPAddress.Loopback, 5022);
                options.Listen(IPAddress.Loopback, 5023, listenOptions =>
                {
                    listenOptions.UseHttps((httpsOptions) =>
                    {
                        var certFileName = "server_cert.pfx";
                        var contentRoot = context.HostingEnvironment.ContentRootPath;
                        X509Certificate2 serverCert;
                        var path = Path.Combine(contentRoot, certFileName);
                        serverCert = new X509Certificate2(path, "<server cert password>");

                        httpsOptions.ServerCertificate = serverCert;
                        // this is what will make the browser display the client certificate dialog
                        httpsOptions.ClientCertificateMode = ClientCertificateMode.RequireCertificate;
                        httpsOptions.CheckCertificateRevocation = false;
                        httpsOptions.ClientCertificateValidation = (certificate2, validationChain, policyErrors) =>
                        {
                            // this is for testing non production certificates, do not use these settings in production
                            validationChain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
                            validationChain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot;
                            validationChain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;
                            validationChain.ChainPolicy.VerificationTime = DateTime.Now;
                            validationChain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 0, 0);
                            validationChain.ChainPolicy.ExtraStore.Add(serverCert);

                            var valid = validationChain.Build(certificate2);
                            if (!valid)
                                return false;

                            // only trust certs that are signed by our CA cert
                            valid = validationChain.ChainElements
                                .Cast<X509ChainElement>()
                                .Any(x => x.Certificate.Thumbprint == serverCert.Thumbprint);

                            return valid;
                        };
                    });
                });
            });
}