我最近想配置一个.net core网站以使用客户端ssl证书身份验证
我找不到一个好的例子,所以我做了一些研究,并决定将结果发布在这里供其他人使用。
最佳答案
在 .net core 2.2 中,您可以在 .UseHttps
方法中将客户端证书配置为选项,同时在 Program.cs
中配置 Kestrel
使用此配置,当用户在浏览器中打开站点时,浏览器将显示一个对话框,要求用户选择客户端证书进行身份验证。如果证书无效,服务器将返回 HTTP 495 SSL 证书错误
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;
};
});
});
});
}
关于c# - 如何在 .Net Core 中使用客户端 SSL 证书,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54057615/