.net core 自颁发ssl证书,及客户端证书验证
.net core 自颁发ssl证书,及客户端证书验证
openshell 颁发证书:
先下载 openshell,下载地址:https://slproweb.com/products/Win32OpenSSL.html
openssl genrsa -out server.key 2048 openssl x509 -req -in server.csr -out server.crt -signkey server.key -days 36500 openssl pkcs12 -export -in server.crt -inkey server.key -out server.pfx
appsettings.json 配置文件:
增加 kestrel 配置https及证书文件;
{ "Kestrel": { "Endpoints": { "HttpsInlineCertAndKeyFile": { "Url": "https://*:5433", "Certificate": { "Path": "./certs/server.pfx", "Password": "123456" } } } } }
//配置客户端连接时必需选择证书,不对证书验证 services.Configure<KestrelServerOptions>(options => { options.ConfigureHttpsDefaults(options => { options.ClientCertificateMode = ClientCertificateMode.RequireCertificate; options.ClientCertificateValidation = (_, _, _) => true; }); }); //证书认证 services.AddAuthentication(CertificateAuthenticationDefaults.AuthenticationScheme) .AddCertificate(options => { options.AllowedCertificateTypes = CertificateTypes.All; options.ValidateCertificateUse = false; options.ValidateValidityPeriod = false; options.ChainTrustValidationMode = System.Security.Cryptography.X509Certificates.X509ChainTrustMode.CustomRootTrust; options.Events = new CertificateAuthenticationEvents { OnCertificateValidated = context => { //验证客户端证书指纹 var thumbprints = context.HttpContext.RequestServices.GetRequiredService<IOptionsMonitor<ThumbprintOptions>>(); if (thumbprints.CurrentValue.Contains(context.ClientCertificate.Thumbprint)) { var claims = new[] { new Claim( ClaimTypes.NameIdentifier, context.ClientCertificate.Subject, ClaimValueTypes.String, context.Options.ClaimsIssuer), }; context.Principal = new ClaimsPrincipal( new ClaimsIdentity(claims, context.Scheme.Name)); context.Success(); } else { context.Fail("证书错误"); } return Task.CompletedTask; } }; });
管道中使用授权认证:
//将http请求重置到 https
app.UseHttpsRedirection();
app.UseCertificateForwarding();
app.UseAuthentication();
app.UseAuthorization();
控制器中增加认证
[Authorize(AuthenticationSchemes = CertificateAuthenticationDefaults.AuthenticationScheme)]
public class textController : ControllerBase