asp.net-core - ASP.NET Core 中的开发证书身份验证问题
问题描述
我正在使用 .NET Core 3.1 和 Microsoft.AspNetCore.Authentication.Certificate 包开发 Web API。
这是我的配置方法:
public void Configure(IApplicationBuilder app) {
//if (env.IsDevelopment()) app.UseDeveloperExceptionPage();
AutofacContainer = app.ApplicationServices.GetAutofacRoot();
app.UseRouting();
app.UseCertificateForwarding();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints => {
endpoints.MapControllers();
});
}
我设置 services.AddAuthentication 如下:
services.AddAuthentication(
CertificateAuthenticationDefaults.AuthenticationScheme)
.AddCertificate(options => {
options.Events = new CertificateAuthenticationEvents {
OnCertificateValidated = context => {
var claims = new[]
{
new Claim(
ClaimTypes.NameIdentifier,
context.ClientCertificate.Subject,
ClaimValueTypes.String,
context.Options.ClaimsIssuer),
new Claim(ClaimTypes.Name,
context.ClientCertificate.Subject,
ClaimValueTypes.String,
context.Options.ClaimsIssuer)
};
context.Principal = new ClaimsPrincipal(
new ClaimsIdentity(claims, context.Scheme.Name));
context.Success();
return Task.CompletedTask;
},
OnAuthenticationFailed = context => {
context.Fail("invalid cert");
return Task.CompletedTask;
}
};
});
在 applicationHost.config 中,这是我的元素:
<access sslFlags="Ssl, SslNegotiateCert, SslRequireCert, Ssl128" />
因此,我的应用程序需要 SSL。
使用我的智能卡上的证书, OnCertificateValidated 触发没有问题。使用有根测试证书,我预计 OnAuthenticationFailed 事件会触发,因为 options.RevocationMode 的默认值为 X509RevocationMode.Online。但是,使用此测试证书,根本不会触发任何事件。
当我将 options.RevocationMode 设置为 X509RevocationMode.NoCheck 时,实际上会为测试证书触发 OnCertificateValidated 事件;这意味着在它失败之前。如果是这种情况,那么为什么 OnAuthenticationFailed 事件没有触发。
更新
我下载了这些符号并单步执行了 CertificateAuthenticationHandler.cs 中的代码。证书验证失败,代码运行
return AuthenticateResult.Fail("Client certificate failed validation.");
但 OnAuthenticationFailed 的处理程序没有触发。
任何人都可以提供任何帮助,我们将不胜感激。
解决方案
长话短说,这种行为是设计使然。
正如我在更新中提到的,当证书正确“验证”时,代码会触发 AuthenticateResult.Fail ;它不会触发 Events.AuthenticationFailed。
我在 GitHub 上提出了一个问题,他们将在下一个版本中更新代码。
推荐阅读
- javascript - 为什么带有特殊字符的字符串在 GET 和 POST 方法中的行为不同?
- c++ - *char 数组到字符串(两次运行代码和两个不同的结果)
- sapui5 - 如何使用 sapui5 sap.ui.table.Table 和大量数据进行大规模更改?
- javascript - JavaScript:未捕获的 SyntaxError:意外的字符串错误 jQuery
- mysql - 插入多个具有 select 语句的数据,并且该 select 语句的 FROM 表与我要插入的表相同
- python - 如何将数组列表转换为一个列表?
- css - CSS中的居中和响应式图像
- c# - 我的地图网络驱动器有问题
- javascript - 如何为将 iframe 的 src 属性建立到不同 html 文档的锚点设置两个版本的 onclick 事件
- azure-traffic-manager - 如何将流量管理器与 Azure 存储静态网站一起使用?