'TCP Client/Server hosted in Kestrel

I would like to create a simple TCP Server / TCP Client and use a Controller to interface with that classes, to then host the controller in a kestrel webserver.

I wanted to use SimpleSockets to create TCP Clients and the Server. The creator of that library describes two ways of instantiating a TCP-Server either by providing an SSL-Certificate or by just creating a TcpListener without the need of an certificate.

It is described here

I want to use the option by providing an ssl-certificate but I cannot figure out how to provide the constructor with that certficate that is managed by the kestrel webserver, is there any way of injecting it (if that is the right way to do it) into the constructor of the TCP-Server?

If yes how would I inject the certificate?

In the code of the webserver I add the certificate like that:

 builder.Services.AddAuthentication(CertificateAuthenticationDefaults.AuthenticationScheme)
        .AddCertificate(options =>
        {
            options.AllowedCertificateTypes = builder.Configuration.GetSection("Authentication").GetSection("CertificateAuthentication").GetValue<CertificateTypes>("AllowedCertificateTypes");
            options.Events = new CertificateAuthenticationEvents
            {
                OnCertificateValidated = context =>
                {
                    var validationService = context.HttpContext.RequestServices.GetService<CertificateValidationService>();
                    if (validationService is not null)
                    {
                        if (validationService.ValidateCertificate(context.ClientCertificate))
                        {
                            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;
                        }
                    }
                    context.Fail("Invalid client certificate");
                    return Task.CompletedTask;
                }
            };
        })
        .AddCertificateCache();

And that is the code of the constructor of my TCP-Server class where I want to inject the certificate into:

public TcpServer(X509Certificate2 certificate)
{
   Listener = new SimpleSocketTcpSslListener(certificate);
}

Thanks in advance.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source