Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4839

How to use self signed certificate in Blazor

$
0
0

On .net 8, I am trying to run in blazor using a self signed certificate that has been added to Local Machine Trusted Root Certificate Authorities. The code is a standard Blazor Web App template with code for kestrel setup, certificates and ports.

The code for the application can be found here.

In the server we have the Main method shown below. This code has a variable useSetup, which controls if standard settings are used or to use the port and self signed certificate (generated by GenerateCert app). When useSetup is false the code runs but does not use the settings in Ports or Certificates directory.When the settings are used we get and IOException in SslStream.cs ReceiveHandshakeFrameAsync where the frameSize is zero. This happens immediately at startup.

With useSetup true setup code show below runs. Is this setup code correct, or is there some other way to do a kestrel setup that sets the port and certificate. Or, is there a problem with GenerateCert app that does not create the certificate correctly? I am not sure what is causing the error. I would like to be able to run in debug and release.

Setup Code

             var httpsConnectionAdapterOptions = new HttpsConnectionAdapterOptions                {                    SslProtocols = System.Security.Authentication.SslProtocols.Tls12,                    ClientCertificateMode = ClientCertificateMode.AllowCertificate,                    ServerCertificate = apiCert                };                builder.WebHost.ConfigureKestrel (                    options =>                    {                        options.ConfigureEndpointDefaults (                            listenOptions =>                                listenOptions.UseHttps ( httpsConnectionAdapterOptions ) );                        options.Listen (                            ipAddress, port );                    } );            }

Main Method

    public static void Main ( string [] args )    {        X509Certificate2 apiCert = null;        X509Certificate2 idpCert = null;        X509Store store = null;        Ports apiPorts = null;        Certificates apiCertificates = null;        var useSetup = true;        try        {            // set url to listen on            // using apiports.json for port            // this is so user can specify port            if ( useSetup )            {                var apiPortsPath = Ports.GetApiPortsFilePath ();                Debug.WriteLine ( "ports.json path: " + apiPortsPath );                if ( !Ports.Exists ( apiPortsPath ) )                    throw new InvalidOperationException ( "FAILED no ports file" );                apiPorts = Ports.LoadPorts ( apiPortsPath );                Debug.WriteLine ( "ApiPort " + apiPorts.Port );                // get certificate to use                // using certificate.json for info                // this so user can use their own certificate                var apiCertsPath = Certificates.GetApiCertsFilePath ();                apiCertificates = new Certificates ();                if ( apiCertificates == null )                    throw new NullReferenceException ( "FAILED to create certificates" );                if ( !apiCertificates.Exists ( apiCertsPath ) )                    throw new InvalidOperationException ( "FAILED no api certificates file" );                apiCertificates.LoadCerts ( apiCertsPath );                Debug.WriteLine ( "Encrypton Cert " + apiCertificates.EncryptionCert );                Debug.WriteLine ( "Signing Cert " + apiCertificates.SigningCert );            }            var builder = WebApplication.CreateBuilder ( args );            if ( useSetup )            {                var port = apiPorts.Port;                var ipAddress = IPAddress.Parse ( "127.0.0.1" );                if ( apiCertificates.CertificateType == CertificateType.File )                {                    var certPath = apiCertificates.EncryptionCert;                    var certPassword = apiCertificates.EncryptionPassword;                    Debug.WriteLine ( "Using file certificate " + certPath );                    apiCert = new X509Certificate2 ( certPath, certPassword );                    if ( apiCert == null )                        throw new NullReferenceException ( "FAILED to get cert from path " + certPath );                    Debug.WriteLine ( "X509Certificate2 created from file" );                }                else                {                    var storeName = apiCertificates.StoreName;                    var storeLocation = apiCertificates.StoreLocation;                    var subject = apiCertificates.EncryptionCert;                    Debug.WriteLine ( "Using stored certificate StoreName: " + storeName +" StoreLocation: " + storeLocation );                    store = new X509Store ( storeName, storeLocation );                    store.Open ( OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly );                    var results = store.Certificates.Find ( X509FindType.FindBySubjectName, subject, false );                    if ( results != null && results.Count > 0 )                        apiCert = results [ 0 ];                    if ( apiCert == null )                        throw new NullReferenceException ( "FAILED to get cert from store" );                    Debug.WriteLine ( "X509Certificate2 created from store" );                }                var httpsConnectionAdapterOptions = new HttpsConnectionAdapterOptions                {                    SslProtocols = System.Security.Authentication.SslProtocols.Tls12,                    ClientCertificateMode = ClientCertificateMode.AllowCertificate,                    ServerCertificate = apiCert                };                builder.WebHost.ConfigureKestrel (                    options =>                    {                        options.ConfigureEndpointDefaults (                            listenOptions =>                                listenOptions.UseHttps ( httpsConnectionAdapterOptions ) );                        options.Listen (                            ipAddress, port );                    } );            }            // Add services to the container.            builder.Services.AddRazorComponents ()                .AddInteractiveServerComponents ()                .AddInteractiveWebAssemblyComponents ();            var app = builder.Build ();            // Configure the HTTP request pipeline.            if ( app.Environment.IsDevelopment () )            {                app.UseWebAssemblyDebugging ();            }            else            {                app.UseExceptionHandler ( "/Error" );                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.                app.UseHsts ();            }            app.UseHttpsRedirection ();            app.UseStaticFiles ();            app.UseAntiforgery ();            app.MapRazorComponents<App> ()                .AddInteractiveServerRenderMode ()                .AddInteractiveWebAssemblyRenderMode ()                .AddAdditionalAssemblies ( typeof ( Client._Imports ).Assembly );            app.Run ();        }        catch ( AggregateException aex )        {            Debug.WriteLine ( "Exception in Gt.WebApi" + aex.ToString () );        }        catch ( Exception ex )        {            Debug.WriteLine ( "Exception in Gt.WebApi", ex );        }        finally        {            if ( store != null )            {                store.Close ();                store.Dispose ();            }            if ( apiCert != null )            {                apiCert.Reset ();                apiCert.Dispose ();            }            if ( idpCert != null )            {                idpCert.Reset ();                idpCert.Dispose ();            }        }    }

Update 1

I was able to get this running by using kestrel configuration that passes in file or store location directly, and generated new exportable cert.

        public static void Main ( string [] args )    {        X509Certificate2 apiCert = null;        X509Certificate2 idpCert = null;        X509Store store = null;        Ports apiPorts = null;        Certificates apiCertificates = null;        var useSetup = true;        try        {            // set url to listen on            // using apiports.json for port            // this is so user can specify port            if ( useSetup )            {                var apiPortsPath = Ports.GetApiPortsFilePath ();                Debug.WriteLine ( "ports.json path: " + apiPortsPath );                if ( !Ports.Exists ( apiPortsPath ) )                    throw new InvalidOperationException ( "FAILED no ports file" );                apiPorts = Ports.LoadPorts ( apiPortsPath );                Debug.WriteLine ( "ApiPort " + apiPorts.Port );                // get certificate to use                // using certificate.json for info                // this so user can use their own certificate                var apiCertsPath = Certificates.GetApiCertsFilePath ();                apiCertificates = new Certificates ();                if ( apiCertificates == null )                    throw new NullReferenceException ( "FAILED to create certificates" );                if ( !apiCertificates.Exists ( apiCertsPath ) )                    throw new InvalidOperationException ( "FAILED no api certificates file" );                apiCertificates.LoadCerts ( apiCertsPath );                Debug.WriteLine ( "Encrypton Cert " + apiCertificates.EncryptionCert );                Debug.WriteLine ( "Signing Cert " + apiCertificates.SigningCert );            }            var builder = WebApplication.CreateBuilder ( args );            if ( useSetup )            {                var port = apiPorts.Port;                var ipAddress = IPAddress.Parse ( "127.0.0.1" );                // this setup works with self signed cert                // but will show as insecure                // not sure what tls defaults are                builder.WebHost.ConfigureKestrel (                    options =>                    {                        var port = apiPorts.Port;                        if ( apiCertificates.CertificateType == CertificateType.File )                        {                            var pfxFilePath = apiCertificates.EncryptionCert;                            var pfxPassword = apiCertificates.EncryptionPassword;                            options.Listen (                                ipAddress, port,                                listenOptions =>                                {                                    // Configure Kestrel to use a certificate from a local .PFX file for hosting HTTPS                                    listenOptions.UseHttps ( pfxFilePath, pfxPassword );                                } );                        }                        else                        {                            var storeName = apiCertificates.StoreName;                            var storeLocation = apiCertificates.StoreLocation;                            var subject = apiCertificates.EncryptionCert;                            options.Listen (                                ipAddress, port,                                listenOptions =>                                {                                    // Configure Kestrel to use a certificate from a local .PFX file for hosting HTTPS                                    listenOptions.UseHttps ( storeName, subject, false, storeLocation );                                } );                        }                    } );            }            // Add services to the container.            builder.Services.AddRazorComponents ()                .AddInteractiveServerComponents ()                .AddInteractiveWebAssemblyComponents ();            builder.Services.AddLogging ( loggingBuilder => loggingBuilder                .AddConsole ()                .AddDebug ()                .SetMinimumLevel ( LogLevel.Trace ) );            var app = builder.Build ();            // Configure the HTTP request pipeline.            if ( app.Environment.IsDevelopment () )            {                app.UseWebAssemblyDebugging ();            }            else            {                app.UseExceptionHandler ( "/Error" );                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.                app.UseHsts ();            }            app.UseHttpsRedirection ();            app.UseStaticFiles ();            app.UseAntiforgery ();            app.MapRazorComponents<App> ()                .AddInteractiveServerRenderMode ()                .AddInteractiveWebAssemblyRenderMode ()                .AddAdditionalAssemblies ( typeof ( Client._Imports ).Assembly );            app.Run ();        }        catch ( AggregateException aex )        {            Debug.WriteLine ( "Exception in Gt.WebApi" + aex.ToString () );        }        catch ( Exception ex )        {            Debug.WriteLine ( "Exception in Gt.WebApi", ex );        }        finally        {            if ( store != null )            {                store.Close ();                store.Dispose ();            }            if ( apiCert != null )            {                apiCert.Reset ();                apiCert.Dispose ();            }            if ( idpCert != null )            {                idpCert.Reset ();                idpCert.Dispose ();            }        }    }

Viewing all articles
Browse latest Browse all 4839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>