首页 > 解决方案 > 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 的处理程序没有触发。

任何人都可以提供任何帮助,我们将不胜感激。

标签: asp.net-coreauthenticationasp.net-web-apipki

解决方案


长话短说,这种行为是设计使然。

正如我在更新中提到的,当证书正确“验证”时,代码会触发 AuthenticateResult.Fail ;它不会触发 Events.AuthenticationFailed。

我在 GitHub 上提出了一个问题,他们将在下一个版本中更新代码。

请参阅https://github.com/dotnet/aspnetcore/issues/30819以供参考


推荐阅读