![](/img/trans.png)
[英]OnCertificateValidated not running - Self-Signed Certificate Client Authentication - ASP.NET Core and Kestrel
[英]Self Hosted Asp Net Core Web server, client authentication with self-signed certificates
我正在测试一个自托管的 Asp Net Core Web 服务器 (Kestrel),我正在努力使用自签名证书进行客户端身份验证。 这是我的启动代码
WebApplicationBuilder webBuilder = WebApplication.CreateBuilder();
var webHostBuilder = builder.WebHost;
X509Certificate2 rootCert = new X509Certificate2(hostCertFilePath, hostCertPassword);
webHostBuilder.ConfigureKestrel(o =>
{
o.ConfigureHttpsDefaults(o =>
{
o.ServerCertificate = rootCert;
o.ClientCertificateMode = ClientCertificateMode.RequireCertificate;
});
});
webHostBuilder.UseKestrel(o =>
{
o.Listen(IPAddress.Parse(myHttpsEndPointIpAddr), myHttpsEndPointPort,
listenOptions =>
{
listenOptions.UseHttps();
});
o.Listen(IPAddress.Parse(myHttpEndPointIpAddr), myHttpEndPointPort);
});
var services = webBuilder.Services;
services.AddTransient<MyCustomCertificateValidationService>();
services
.AddAuthentication(CertificateAuthenticationDefaults.AuthenticationScheme)
.AddCertificate(options =>
{
options.AllowedCertificateTypes = CertificateTypes.SelfSigned;
options.Events = new CertificateAuthenticationEvents
{
OnCertificateValidated = context =>
{
var validationService = context.HttpContext.RequestServices
.GetService<MyCustomCertificateValidationService>();
if (validationService.ValidateCertificate(context.ClientCertificate))
{
context.Success();
}
else
{
context.Fail("invalid cert");
}
return Task.CompletedTask;
},
OnAuthenticationFailed = context =>
{
context.Fail("invalid cert");
return Task.CompletedTask;
}
};
});
...
var app = webBuilder.Build();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
这是我的自定义认证 class
public class MyCustomCertificateValidationService
{
public bool ValidateCertificate(X509Certificate2 clientCertificate)
{
// todo: check certificate thumbnail
return false;
}
}
但是,即使 MyCustomCertificateValidationService 有一个返回 false 的方法 ValidateCertificate(),当客户端访问 url 时,仍然会调用 controller 方法,路由指向 controller 方法。 这是日志中显示的内容:
...
AspNetCore.Routing.EndpointRoutingMiddleware : Request matched endpoint ‘GetMyData…‘
AspNetCore.Authentication.Certificate.CertificateAuthenticationHandler : Certificate was not authenticated. Failure message: invalid cert
AspNetCore.Routing.EndpointMiddleware : Executing endpoint ‘GetMyData…‘
...
为什么仍然调用 controller 方法的任何线索?
“应用程序有一个用例,在某些测试环境中也应该允许未经授权的调用(超过 http://...)。如果可能的话,我更愿意使用设置参数来动态决定是否访问 http是否允许,而不是将其“硬编码”为 [Authorize] 属性”
你当然可以这样做。 肯定有一种方便的方法可以使用中间件来实现您的要求。 请尝试下面的代码片段:
Http/Https Request Middleare 基于环境:
public class CustomHttpHttpsRequestMiddleware
{
private readonly RequestDelegate next;
public CustomHttpHttpsRequestMiddleware(RequestDelegate next)
{
this.next = next;
}
public async Task InvokeAsync(HttpContext context)
{
var env = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
//env = "Production";
if (env == "Development")
{
await next(context);
}
else
{
if (!context.Request.IsHttps)
{
context.Response.StatusCode = StatusCodes.Status400BadRequest;
await context.Response.WriteAsync("HTTPS required!");
}
}
}
}
注意:在应用程序request context
,我们正在检查两个重要值,首先如果请求是安全的意味着cIsHttps
和application environment
,在Development
环境中我们将允许http
请求。 因此,除了dev
或任何基于我们要求的http
env
。
在 Program.cs 上注册中间件:
app.UseMiddleware<CustomHttpHttpsRequestMiddleware>();
注意:确保您遵循了正确的中间件顺序。 为了避免短路,您可以将此中间件放在所有当前中间件的下方。
Output:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.