question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

The method that validates the client certificate is not executed

See original GitHub issue

Is there an existing issue for this?

  • I have searched the existing issues

Describe the bug

I am trying to implement the validation of the client certificate, but the method that implements that is not execute.

I am following this documentation:

This is the code in my program.cs file of the ASP Core project:

Environment.CurrentDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!;


var builder = WebApplication.CreateBuilder(args);

//Para poder acceder a la configuración
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();





try
{
    builder.WebHost.ConfigureKestrel((context, options) =>
    {
        string miStrCertificado = File.ReadAllText(builder.Configuration.GetSection("Certificados:Certificado").Value!);
        string miStrKey = File.ReadAllText(builder.Configuration.GetSection("Certificados:Key").Value!);
        X509Certificate2 miCertficadoX509 = X509Certificate2.CreateFromPem(miStrCertificado, miStrKey);




        X509Certificate2 miCertificado2 = new X509Certificate2(miCertficadoX509.Export(X509ContentType.Pkcs12));

        miCertficadoX509.Dispose();

        options.ListenAnyIP(Convert.ToInt32(builder.Configuration.GetSection("Servidor:Puerto").Value!), listenOptions =>
        {
            listenOptions.Protocols = HttpProtocols.Http2;
            listenOptions.UseHttps(miCertificado2);
        });


        options.ConfigureHttpsDefaults(miHttpsOptions =>
        {
            miHttpsOptions.ServerCertificate = miCertificado2;
            miHttpsOptions.ClientCertificateMode = ClientCertificateMode.RequireCertificate;
            miHttpsOptions.ClientCertificateValidation += ValidarCertificadoCliente;
        });
    });


    

    builder.Services.AddHttpContextAccessor();


    ConfigurarDependencias(builder.Services, builder.Configuration);



    builder.Services.AddGrpc();
    builder.Services.AddCodeFirstGrpc();



    builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(builder.Configuration.GetSection("JwtAuthApp.Server:JwtTokenService:ClaveCifradoToken").Value!)),
                RequireExpirationTime = true,
                RequireSignedTokens = true,
                ClockSkew = TimeSpan.FromSeconds(10),

                ValidateIssuer = false,
                ValidateAudience = false,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,
            };
        });




    builder.Services.AddAuthentication(
         CertificateAuthenticationDefaults.AuthenticationScheme)
         .AddCertificate(options =>
         {
             options.AllowedCertificateTypes = CertificateTypes.SelfSigned;
             options.Events = new CertificateAuthenticationEvents
             {
                 OnCertificateValidated = context =>
                 {
                     if (ValidateCertificate(context.ClientCertificate))
                     {
                         context.Success();
                     }
                     else
                     {
                         context.Fail("invalid cert");
                     }


                     return Task.CompletedTask;
                 },
                 OnAuthenticationFailed = context =>
                 {
                     context.Fail("invalid cert");
                     return Task.CompletedTask;
                 }
             };
         });




    builder.Services.AddAuthorization();





    var app = builder.Build();



    app.UseRouting();
    app.UseCertificateForwarding();
    app.UseAuthentication();
    app.UseAuthorization();
    app.MapGrpcService<MyGrpcService>();




    await app.RunAsync();
}
catch (Exception ex)
{
    miLogger.Error($"El servidor CMMS se ha detenido por un error. {ex.Message}");
}





bool ValidarCertificadoCliente(X509Certificate2 clientCertificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
    return true;
}

The method ValidateCertificate() is not execute.

Thanks.

Expected Behavior

Run the method that validates the client certificate.

Steps To Reproduce

No response

Exceptions (if any)

No response

.NET Version

.NET Core 7

Anything else?

No response

Issue Analytics

  • State:closed
  • Created 5 months ago
  • Comments:11 (9 by maintainers)

github_iconTop GitHub Comments

1reaction
amcaseycommented, May 1, 2023

Normally, I would grab this as a cert issue, but it seems like @mitchdenny has already responded pretty extensively to prior facets of this question.

0reactions
msftbot[bot]commented, May 8, 2023

This issue has been automatically marked as stale because it has been marked as requiring author feedback but has not had any activity for 4 days. It will be closed if no further activity occurs within 3 days of this comment. If it is closed, feel free to comment when you are able to provide the additional information and we will re-investigate.

See our Issue Management Policies for more information.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Client certificate validation with custom store not working
For one of our projects we require only one endpoint of a service to have client certificate validation. The code will be running...
Read more >
Client Certificate revisited….How to troubleshoot ...
This error message means that the client sent a certificate, but either the certificate shows up as revoked in the issuing authority's ...
Read more >
SSL Client Certificate Authentication not working. What am I ...
I want to enable SSL client certificate authentication using CA API Gateway ... provide a list of certs, so the client can validate...
Read more >
How to validate a client certificate
The certificate has to be validated against its signing authority This is accomplished by verifying the signature on the certificate with the ...
Read more >
Using client certificates in .NET part 4
NET part 4: working with client certificates in code. Introduction ... The Validate method will throw an exception if the validation fails.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found