.net core 自颁发ssl证书,及客户端证书验证
.net core 自颁发ssl证书,及客户端证书验证
openshell 颁发证书:
先下载 openshell,下载地址:https://slproweb.com/products/Win32OpenSSL.html
1 2 3 | 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及证书文件;
1 2 3 4 5 6 7 8 9 10 11 12 13 | { "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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?