public static void Main(string[] args) { var cert = CertificateLoader.LoadFromStoreCert("localhost", StoreName.My.ToString(), StoreLocation.CurrentUser, true); var hostBuilder = new HostBuilder() .ConfigureLogging((_, factory) => { factory.SetMinimumLevel(LogLevel.Trace); factory.AddConsole(); }) .ConfigureWebHost(webHost => { webHost.UseKestrel() // Things like APLN and cert should be able to be passed from corefx into bedrock .UseQuic(options => { options.Certificate = cert; options.RegistrationName = "Quic"; options.Alpn = "h3-24"; options.IdleTimeout = TimeSpan.FromHours(1); }) .ConfigureKestrel((context, options) => { var basePort = 5555; options.Listen(IPAddress.Any, basePort, listenOptions => { listenOptions.UseHttps(); listenOptions.Protocols = HttpProtocols.Http3; }); }) .UseStartup <Startup>(); }); hostBuilder.Build().Run(); }
private static X509Certificate2 LoadFromStoreCert(CertificateConfig certInfo) { var subject = certInfo.Subject !; var storeName = string.IsNullOrEmpty(certInfo.Store) ? StoreName.My.ToString() : certInfo.Store; var location = certInfo.Location; var storeLocation = StoreLocation.CurrentUser; if (!string.IsNullOrEmpty(location)) { storeLocation = (StoreLocation)Enum.Parse(typeof(StoreLocation), location, ignoreCase: true); } var allowInvalid = certInfo.AllowInvalid ?? false; return(CertificateLoader.LoadFromStoreCert(subject, storeName, storeLocation, allowInvalid)); }
public static string GetAccessTokenV2(Uri serviceRoot) { string authority = "https://login.microsoftonline.com/" + "72f988bf-86f1-41af-91ab-2d7cd011db47"; string resource = "https://disco.crm10.dynamics.com/"; string clientId = "851c8aca-8a2a-40c0-8bb8-67f6756d56bd"; AuthenticationContext authContext = new AuthenticationContext(authority, false); // new var clientCertName = "serviceauth.local-operations365.dynamics.com"; var certificate = CertificateLoader.LoadFromStoreCert(clientCertName, "My", StoreLocation.LocalMachine, allowInvalid: false); var clientAssertionCertificate = new ClientAssertionCertificate(clientId, certificate); AuthenticationResult authResult = authContext.AcquireTokenAsync(resource, clientAssertionCertificate, true).Result; return(authResult.AccessToken); }
public IHostBuilder CreateHostBuilder(string[] args) => Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup <Startup>(); webBuilder.UseConfiguration(Configuration); webBuilder.UseDefaultServiceProvider((context, options) => { options.ValidateScopes = isDevelopment; // context.HostingEnvironment.IsDevelopment(); }); webBuilder.UseKestrel((context, options) => { //var isDevelopment = context.HostingEnvironment.IsDevelopment(); options.AddServerHeader = false; options.Limits.MaxRequestBodySize = 10 * 1024 * 1024; // 10Mb, options.Listen(IPAddress.Any, 80); var file = EnsureDataFile(isDevelopment, "domaincert.pfx", Platform.DtpServerDataPath); // GetPfxFile if (File.Exists(file)) { options.Listen(IPAddress.Any, 443, listenOptions => { listenOptions.UseHttps(file, "123"); }); Log.Information("Certiticate loaded!"); } else { try { var cert = CertificateLoader.LoadFromStoreCert("localhost", "My", StoreLocation.CurrentUser, allowInvalid: true); options.Listen(IPAddress.Loopback, 443, listenOptions => { listenOptions.UseHttps(cert); }); } catch { Log.Warning("Localhost https certificate not supported."); } } }); webBuilder.CaptureStartupErrors(true); webBuilder.UseSerilog(); });
/// <summary> /// Configures TLS. /// </summary> /// <param name="builder">The builder to configure.</param> /// <param name="storeName">The certificate store to load the certificate from.</param> /// <param name="subject">The subject name for the certificate to load.</param> /// <param name="allowInvalid">Indicates if invalid certificates should be considered, such as self-signed certificates.</param> /// <param name="location">The store location to load the certificate from.</param> /// <param name="configureOptions">An Action to configure the <see cref="TlsOptions"/>.</param> /// <returns>The builder.</returns> public static IClientBuilder UseTls( this IClientBuilder builder, StoreName storeName, string subject, bool allowInvalid, StoreLocation location, Action <TlsOptions> configureOptions) { if (configureOptions == null) { throw new ArgumentNullException(nameof(configureOptions)); } return(builder.UseTls( CertificateLoader.LoadFromStoreCert(subject, storeName.ToString(), location, allowInvalid, server: false), configureOptions)); }
/// <summary> /// Configures the ListenOptions for the Kestrel-Server /// </summary> /// <param name="options">the default-endpoint-listener options</param> public void ConfigureEndPointDefaults(ListenOptions options) { options.UseHttps(ho => { if (certificateAutoSelect) { ho.ServerCertificateSelector = (context, name) => { return(CertificateLoader.LoadFromStoreCert(name, StoreName.My.ToString(), StoreLocation.LocalMachine, false)); }; } else { ho.ServerCertificate = new X509Certificate2(pathToCertificate, certificatePassword.Decrypt().Secure(), X509KeyStorageFlags.PersistKeySet); } }); }
public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup <Startup>() .UseKestrel((context, options) => { options.ListenAnyIP(5005, listenOptions => { listenOptions.UseHttps(httpsOptions => { var localhostCert = CertificateLoader.LoadFromStoreCert( "localhost", "My", StoreLocation.CurrentUser, allowInvalid: true); httpsOptions.ServerCertificateSelector = (connectionContext, name) => localhostCert; }); }); }) .UseContentRoot(Directory.GetCurrentDirectory());
public void ConfigureServices(IServiceCollection services) { services.AddSingleton <IConfiguration>(Configuration); var authoritySettings = Configuration.GetSection("AuthoritySettings").Get <AuthoritySettings>() ?? throw new ArgumentNullException( "AuthoritySettings section is empty, invalid, or not present"); services.AddScoped <IUserRepository, UserRepository>(); services.Configure <AuthoritySettings>(Configuration.GetSection("AuthoritySettings")); services.AddIdentityServer(options => { }) .AddSigningCredential(CertificateLoader.LoadFromStoreCert("Ws-PC-70", "Root", StoreLocation.LocalMachine, false)) .AddInMemoryApiResources(Config.GetApiResources()) .AddInMemoryApiScopes(Config.GetApiScopes()) .AddInMemoryIdentityResources(Config.GetIdentityResources()) .AddResourceOwnerValidator <ResourceOwnerPasswordValidator>() .AddProfileService <ProfileService>() .AddClientStore <ClientsStore>() .AddJwtBearerClientAuthentication(); services.AddAuthentication() .AddJwtBearer(jwt => { jwt.Authority = authoritySettings.AuthorityApiEndpoint; jwt.TokenValidationParameters.ValidateAudience = true; jwt.SaveToken = true; }); services.AddCors(options => { options.AddPolicy("CorsPolicy", builder => builder .WithOrigins(new[] { authoritySettings.DefaultRedirectUri }) .WithHeaders("*") .WithMethods("*") .AllowCredentials()); }); services.AddRazorPages(); services.AddSingleton <IActionContextAccessor, ActionContextAccessor>(); }
public static string GetAccessToken(string userName, string password, Uri serviceRoot) { var targetServiceUrl = GetUriBuilderWithVersion(serviceRoot); string _resource; string _authority; // Obtain the Azure Active Directory Authentication Library (ADAL) authentication context. AuthenticationParameters ap; //ap = GetAuthorityFromTargetService(targetServiceUrl.Uri); //AuthenticationContext authContext = new AuthenticationContext(ap.Authority, false); ap = AuthenticationParameters.CreateFromResponseAuthenticateHeader("Bearer authorization_uri=https://login.microsoftonline.com/common/oauth2/authorize,resource_id=https://globaldisco.crm10.dynamics.com/"); _authority = ap.Authority; _resource = ap.Resource; AuthenticationContext authContext = new AuthenticationContext(_authority, false); //AuthenticationContext authContext = new AuthenticationContext(authority, false); //Note that an Azure AD access token has finite lifetime, default expiration is 60 minutes. AuthenticationResult authResult; if (userName != string.Empty && password != string.Empty) { UserPasswordCredential cred = new UserPasswordCredential(userName, password); authResult = authContext.AcquireTokenAsync(_resource, clientId, cred).Result; } else { // new var clientCertName = "serviceauth.local-operations365.dynamics.com"; var certificate = CertificateLoader.LoadFromStoreCert(clientCertName, "My", StoreLocation.LocalMachine, allowInvalid: false); var clientAssertionCertificate = new ClientAssertionCertificate(clientId, certificate); authResult = authContext.AcquireTokenAsync(_resource, clientAssertionCertificate, true).Result; // old //PlatformParameters platformParameters = new PlatformParameters(PromptBehavior.Auto); //authResult = authContext.AcquireTokenAsync(ap.Resource, clientId, new Uri(redirectUrl), platformParameters).Result; } return(authResult.AccessToken); }
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup <Startup>(); webBuilder.UseKestrel((context, serverOptions) => { serverOptions.Configure(context.Configuration.GetSection("Kestrel")) .Endpoint("HTTPS", listenOptions => { listenOptions.HttpsOptions.SslProtocols = System.Security.Authentication.SslProtocols.Tls12; }); }); webBuilder.ConfigureKestrel(options => { options.ConfigureHttpsDefaults(listenOptions => { listenOptions.ServerCertificate = CertificateLoader.LoadFromStoreCert("Ws-PC-70", "Root", StoreLocation.LocalMachine, false); }); }); });
public static void ServerCertificateSelector(string[] args) { // <snippet_ServerCertificateSelector> var builder = WebApplication.CreateBuilder(args); builder.WebHost.ConfigureKestrel(serverOptions => { serverOptions.ListenAnyIP(5005, listenOptions => { listenOptions.UseHttps(httpsOptions => { var localhostCert = CertificateLoader.LoadFromStoreCert( "localhost", "My", StoreLocation.CurrentUser, allowInvalid: true); var exampleCert = CertificateLoader.LoadFromStoreCert( "example.com", "My", StoreLocation.CurrentUser, allowInvalid: true); var subExampleCert = CertificateLoader.LoadFromStoreCert( "sub.example.com", "My", StoreLocation.CurrentUser, allowInvalid: true); var certs = new Dictionary <string, X509Certificate2>( StringComparer.OrdinalIgnoreCase) { ["localhost"] = localhostCert, ["example.com"] = exampleCert, ["sub.example.com"] = subExampleCert }; httpsOptions.ServerCertificateSelector = (connectionContext, name) => { if (name is not null && certs.TryGetValue(name, out var cert)) { return(cert); } return(exampleCert); }; }); }); });
public static void Main(string[] args) { var cert = CertificateLoader.LoadFromStoreCert("localhost", StoreName.My.ToString(), StoreLocation.CurrentUser, false); var hostBuilder = new HostBuilder() .ConfigureLogging((_, factory) => { factory.SetMinimumLevel(LogLevel.Trace); factory.AddConsole(); }) .ConfigureWebHost(webHost => { webHost.UseKestrel() .UseQuic(options => { options.Certificate = cert; // Shouldn't need this either here. options.Alpn = "h3-29"; // Shouldn't need to populate this as well. options.IdleTimeout = TimeSpan.FromHours(1); }) .ConfigureKestrel((context, options) => { var basePort = 5557; options.EnableAltSvc = true; options.Listen(IPAddress.Any, basePort, listenOptions => { listenOptions.UseHttps(httpsOptions => { httpsOptions.ServerCertificate = cert; }); listenOptions.UseConnectionLogging(); listenOptions.Protocols = HttpProtocols.Http3; }); }) .UseStartup <Startup>(); }); hostBuilder.Build().Run(); }
static async Task Main(string[] args) { var host = new HostBuilder() .ConfigureLogging(loggingBuilder => { loggingBuilder.AddConsole(); loggingBuilder.SetMinimumLevel(LogLevel.Error); }) .ConfigureServices(services => { services.AddSingleton <IConnectionFactory, MsQuicConnectionFactory>(); services.AddSingleton <MsQuicClientService>(); services.AddOptions <MsQuicTransportOptions>(); services.Configure <MsQuicTransportOptions>((options) => { options.Alpn = "QuicTest"; options.RegistrationName = "Quic-AspNetCore-client"; options.Certificate = CertificateLoader.LoadFromStoreCert("localhost", StoreName.My.ToString(), StoreLocation.CurrentUser, true); options.IdleTimeout = TimeSpan.FromHours(1); }); }) .Build(); await host.Services.GetService <MsQuicClientService>().RunAsync(); }
/// <summary> /// Configure Kestrel to use HTTPS. /// </summary> /// <param name="listenOptions">The <see cref="ListenOptions"/> to configure.</param> /// <param name="storeName">The certificate store to load the certificate from.</param> /// <param name="subject">The subject name for the certificate to load.</param> /// <param name="allowInvalid">Indicates if invalid certificates should be considered, such as self-signed certificates.</param> /// <param name="location">The store location to load the certificate from.</param> /// <param name="configureOptions">An Action to configure the <see cref="HttpsConnectionAdapterOptions"/>.</param> /// <returns>The <see cref="ListenOptions"/>.</returns> public static ListenOptions UseHttps(this ListenOptions listenOptions, StoreName storeName, string subject, bool allowInvalid, StoreLocation location, Action <HttpsConnectionAdapterOptions> configureOptions) { return(listenOptions.UseHttps(CertificateLoader.LoadFromStoreCert(subject, storeName.ToString(), location, allowInvalid), configureOptions)); }
public static void Main(string[] args) { var cert = CertificateLoader.LoadFromStoreCert("localhost", StoreName.My.ToString(), StoreLocation.CurrentUser, true); var hostBuilder = new WebHostBuilder() .ConfigureLogging((_, factory) => { factory.SetMinimumLevel(LogLevel.Debug); factory.AddConsole(); }) .UseKestrel() .UseMsQuic(options => { options.Certificate = cert; options.RegistrationName = "AspNetCore-MsQuic"; options.Alpn = "QuicTest"; options.IdleTimeout = TimeSpan.FromHours(1); }) .ConfigureKestrel((context, options) => { var basePort = 5555; options.Listen(IPAddress.Any, basePort, listenOptions => { listenOptions.Use((next) => { return(async connection => { var streamFeature = connection.Features.Get <IQuicStreamListenerFeature>(); if (streamFeature != null) { while (true) { var connectionContext = await streamFeature.AcceptAsync(); if (connectionContext == null) { return; } _ = next(connectionContext); } } else { await next(connection); } }); }); async Task EchoServer(ConnectionContext connection) { // For graceful shutdown try { while (true) { var result = await connection.Transport.Input.ReadAsync(); if (result.IsCompleted) { break; } await connection.Transport.Output.WriteAsync(result.Buffer.ToArray()); connection.Transport.Input.AdvanceTo(result.Buffer.End); } } catch (OperationCanceledException) { } } listenOptions.Run(EchoServer); }); }) .UseStartup <Startup>(); hostBuilder.Build().Run(); }
public static Task Main(string[] args) { TaskScheduler.UnobservedTaskException += (sender, e) => { Console.WriteLine("Unobserved exception: {0}", e.Exception); }; var hostBuilder = new WebHostBuilder() .ConfigureLogging((_, factory) => { factory.SetMinimumLevel(LogLevel.Debug); factory.AddConsole(); }) .ConfigureAppConfiguration((hostingContext, config) => { var env = hostingContext.HostingEnvironment; config.AddJsonFile("appsettings.json", optional: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true); }) .UseKestrel((context, options) => { if (context.HostingEnvironment.IsDevelopment()) { ShowConfig(context.Configuration); } var basePort = context.Configuration.GetValue <int?>("BASE_PORT") ?? 5000; options.ConfigureEndpointDefaults(opt => { opt.NoDelay = true; }); options.ConfigureHttpsDefaults(httpsOptions => { httpsOptions.SslProtocols = SslProtocols.Tls12; }); // Run callbacks on the transport thread options.ApplicationSchedulingMode = SchedulingMode.Inline; options.Listen(IPAddress.Loopback, basePort, listenOptions => { // Uncomment the following to enable Nagle's algorithm for this endpoint. //listenOptions.NoDelay = false; listenOptions.UseConnectionLogging(); }); options.Listen(IPAddress.Loopback, basePort + 1, listenOptions => { listenOptions.UseHttps(); listenOptions.UseConnectionLogging(); }); options.ListenLocalhost(basePort + 2, listenOptions => { // Use default dev cert listenOptions.UseHttps(); }); options.ListenAnyIP(basePort + 3); options.ListenAnyIP(basePort + 4, listenOptions => { listenOptions.UseHttps(StoreName.My, "localhost", allowInvalid: true); }); options.ListenAnyIP(basePort + 5, listenOptions => { listenOptions.UseHttps(httpsOptions => { var localhostCert = CertificateLoader.LoadFromStoreCert("localhost", "My", StoreLocation.CurrentUser, allowInvalid: true); httpsOptions.ServerCertificateSelector = (features, name) => { // Here you would check the name, select an appropriate cert, and provide a fallback or fail for null names. return(localhostCert); }; }); }); options .Configure() .Endpoint(IPAddress.Loopback, basePort + 6) .LocalhostEndpoint(basePort + 7) .Load(); options .Configure(context.Configuration.GetSection("Kestrel")) .Endpoint("NamedEndpoint", opt => { opt.ListenOptions.NoDelay = true; }) .Endpoint("NamedHttpsEndpoint", opt => { opt.HttpsOptions.SslProtocols = SslProtocols.Tls12; }); options.UseSystemd(); // The following section should be used to demo sockets //options.ListenUnixSocket("/tmp/kestrel-test.sock"); }) .UseContentRoot(Directory.GetCurrentDirectory()) .UseStartup <Startup>(); if (string.Equals(Process.GetCurrentProcess().Id.ToString(), Environment.GetEnvironmentVariable("LISTEN_PID"))) { // Use libuv if activated by systemd, since that's currently the only transport that supports being passed a socket handle. hostBuilder.UseLibuv(options => { // Uncomment the following line to change the default number of libuv threads for all endpoints. // options.ThreadCount = 4; }); } return(hostBuilder.Build().RunAsync()); }
public static void Main(string[] args) { var hostBuilder = new HostBuilder() .ConfigureLogging((_, factory) => { factory.SetMinimumLevel(LogLevel.Trace); factory.AddSimpleConsole(o => o.TimestampFormat = "[HH:mm:ss.fff] "); }) .ConfigureWebHost(webHost => { var cert = CertificateLoader.LoadFromStoreCert("localhost", StoreName.My.ToString(), StoreLocation.CurrentUser, false); webHost.UseKestrel() .ConfigureKestrel((context, options) => { options.ListenAnyIP(5000, listenOptions => { listenOptions.UseConnectionLogging(); listenOptions.Protocols = HttpProtocols.Http1AndHttp2; }); options.Listen(IPAddress.Any, 5001, listenOptions => { listenOptions.UseHttps(); listenOptions.UseConnectionLogging(); listenOptions.Protocols = HttpProtocols.Http1AndHttp2AndHttp3; }); options.ListenAnyIP(5002, listenOptions => { listenOptions.UseConnectionLogging(); listenOptions.UseHttps(StoreName.My, "localhost"); listenOptions.Protocols = HttpProtocols.Http3; }); options.ListenAnyIP(5003, listenOptions => { listenOptions.UseHttps(httpsOptions => { // ConnectionContext is null httpsOptions.ServerCertificateSelector = (context, host) => cert; }); listenOptions.UseConnectionLogging(); listenOptions.Protocols = HttpProtocols.Http1AndHttp2AndHttp3; }); // No SslServerAuthenticationOptions callback is currently supported by QuicListener options.ListenAnyIP(5004, listenOptions => { listenOptions.UseHttps(httpsOptions => { httpsOptions.OnAuthenticate = (_, sslOptions) => sslOptions.ServerCertificate = cert; }); listenOptions.UseConnectionLogging(); listenOptions.Protocols = HttpProtocols.Http1AndHttp2; }); // ServerOptionsSelectionCallback isn't currently supported by QuicListener options.ListenAnyIP(5005, listenOptions => { ServerOptionsSelectionCallback callback = (SslStream stream, SslClientHelloInfo clientHelloInfo, object state, CancellationToken cancellationToken) => { var options = new SslServerAuthenticationOptions() { ServerCertificate = cert, }; return(new ValueTask <SslServerAuthenticationOptions>(options)); }; listenOptions.UseHttps(callback, state: null); listenOptions.Protocols = HttpProtocols.Http1AndHttp2; }); // TlsHandshakeCallbackOptions (ServerOptionsSelectionCallback) isn't currently supported by QuicListener options.ListenAnyIP(5006, listenOptions => { listenOptions.UseHttps(new TlsHandshakeCallbackOptions() { OnConnection = context => { var options = new SslServerAuthenticationOptions() { ServerCertificate = cert, }; return(new ValueTask <SslServerAuthenticationOptions>(options)); }, }); listenOptions.UseConnectionLogging(); listenOptions.Protocols = HttpProtocols.Http1AndHttp2; }); }) .UseStartup <Startup>(); }); var host = hostBuilder.Build(); // Listener needs to be configured before host (and HTTP/3 endpoints) start up. using var httpEventSource = new HttpEventSourceListener(host.Services.GetRequiredService <ILoggerFactory>()); host.Run(); }
private static X509Certificate2 ServerCertificateSelector(ConnectionContext connection, string sni) { return(CertificateLoader.LoadFromStoreCert(Settings.Current.GameRuntimeSslSubject, Settings.Current.GameRuntimeSslStore, StoreLocation.LocalMachine, false));; }
public static void Main(string[] args) { var hostBuilder = new HostBuilder() .ConfigureLogging((_, factory) => { factory.SetMinimumLevel(LogLevel.Trace); factory.AddConsole(); }) .ConfigureWebHost(webHost => { webHost.UseKestrel() .ConfigureKestrel((context, options) => { var cert = CertificateLoader.LoadFromStoreCert("localhost", StoreName.My.ToString(), StoreLocation.CurrentUser, false); options.ConfigureHttpsDefaults(httpsOptions => { httpsOptions.ServerCertificate = cert; }); options.ListenAnyIP(5000, listenOptions => { listenOptions.UseConnectionLogging(); listenOptions.Protocols = HttpProtocols.Http1AndHttp2; }); options.ListenAnyIP(5001, listenOptions => { listenOptions.UseHttps(); listenOptions.UseConnectionLogging(); listenOptions.Protocols = HttpProtocols.Http1AndHttp2AndHttp3; }); options.ListenAnyIP(5002, listenOptions => { listenOptions.UseHttps(StoreName.My, "localhost"); listenOptions.UseConnectionLogging(); listenOptions.Protocols = HttpProtocols.Http3; }); options.ListenAnyIP(5003, listenOptions => { listenOptions.UseHttps(httpsOptions => { httpsOptions.ServerCertificateSelector = (_, _) => cert; }); listenOptions.UseConnectionLogging(); listenOptions.Protocols = HttpProtocols.Http1AndHttp2; // TODO: http3 }); options.ListenAnyIP(5004, listenOptions => { listenOptions.UseHttps(new TlsHandshakeCallbackOptions() { OnConnection = context => { var options = new SslServerAuthenticationOptions() { ServerCertificate = cert, }; return(new ValueTask <SslServerAuthenticationOptions>(options)); }, }); listenOptions.UseConnectionLogging(); listenOptions.Protocols = HttpProtocols.Http1AndHttp2; // TODO: http3 }); }) .UseStartup <Startup>(); }); hostBuilder.Build().Run(); }
public static Task Main(string[] args) { TaskScheduler.UnobservedTaskException += (sender, e) => { Console.WriteLine("Unobserved exception: {0}", e.Exception); }; var hostBuilder = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseKestrel((context, options) => { if (context.HostingEnvironment.IsDevelopment()) { ShowConfig(context.Configuration); } var basePort = context.Configuration.GetValue <int?>("BASE_PORT") ?? 5000; options.ConfigureHttpsDefaults(httpsOptions => { httpsOptions.SslProtocols = SslProtocols.Tls12; }); options.Listen(IPAddress.Loopback, basePort, listenOptions => { // Uncomment the following to enable Nagle's algorithm for this endpoint. //listenOptions.NoDelay = false; listenOptions.UseConnectionLogging(); }); options.Listen(IPAddress.Loopback, basePort + 1, listenOptions => { listenOptions.UseHttps(); listenOptions.UseConnectionLogging(); }); options.ListenLocalhost(basePort + 2, listenOptions => { // Use default dev cert listenOptions.UseHttps(); }); options.ListenAnyIP(basePort + 3); options.ListenAnyIP(basePort + 4, listenOptions => { listenOptions.UseHttps(StoreName.My, "localhost", allowInvalid: true); }); options.ListenAnyIP(basePort + 5, listenOptions => { var localhostCert = CertificateLoader.LoadFromStoreCert("localhost", "My", StoreLocation.CurrentUser, allowInvalid: true); listenOptions.UseHttps((stream, clientHelloInfo, state, cancellationToken) => { // Here you would check the name, select an appropriate cert, and provide a fallback or fail for null names. var serverName = clientHelloInfo.ServerName; if (serverName != null && serverName != "localhost") { throw new AuthenticationException($"The endpoint is not configured for server name '{clientHelloInfo.ServerName}'."); } return(new ValueTask <SslServerAuthenticationOptions>(new SslServerAuthenticationOptions { ServerCertificate = localhostCert })); }, state: null); }); options .Configure() .Endpoint(IPAddress.Loopback, basePort + 6) .LocalhostEndpoint(basePort + 7) .Load(); // reloadOnChange: true is the default options .Configure(context.Configuration.GetSection("Kestrel"), reloadOnChange: true) .Endpoint("NamedEndpoint", opt => { }) .Endpoint("NamedHttpsEndpoint", opt => { opt.HttpsOptions.SslProtocols = SslProtocols.Tls12; }); options.UseSystemd(); // The following section should be used to demo sockets //options.ListenUnixSocket("/tmp/kestrel-test.sock"); }) .UseContentRoot(Directory.GetCurrentDirectory()) .UseStartup <Startup>(); if (string.Equals(Process.GetCurrentProcess().Id.ToString(CultureInfo.InvariantCulture), Environment.GetEnvironmentVariable("LISTEN_PID"))) { // Use libuv if activated by systemd, since that's currently the only transport that supports being passed a socket handle. #pragma warning disable CS0618 webHostBuilder.UseLibuv(options => { // Uncomment the following line to change the default number of libuv threads for all endpoints. // options.ThreadCount = 4; }); #pragma warning restore CS0618 } }) .ConfigureLogging((_, factory) => { factory.SetMinimumLevel(LogLevel.Debug); factory.AddConsole(); }) .ConfigureAppConfiguration((hostingContext, config) => { var env = hostingContext.HostingEnvironment; config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true); }); return(hostBuilder.Build().RunAsync()); }
public static void Main(string[] args) { var hostBuilder = new HostBuilder() .ConfigureLogging((_, factory) => { factory.SetMinimumLevel(LogLevel.Trace); factory.AddConsole(); }) .ConfigureWebHost(webHost => { webHost.UseKestrel() .ConfigureKestrel((context, options) => { var cert = CertificateLoader.LoadFromStoreCert("localhost", StoreName.My.ToString(), StoreLocation.CurrentUser, false); options.ConfigureHttpsDefaults(httpsOptions => { httpsOptions.ServerCertificate = cert; // httpsOptions.ClientCertificateMode = ClientCertificateMode.AllowCertificate; // httpsOptions.AllowAnyClientCertificate(); }); options.ListenAnyIP(5000, listenOptions => { listenOptions.UseConnectionLogging(); listenOptions.Protocols = HttpProtocols.Http1AndHttp2; }); options.ListenAnyIP(5001, listenOptions => { listenOptions.UseHttps(); listenOptions.UseConnectionLogging(); listenOptions.Protocols = HttpProtocols.Http1AndHttp2AndHttp3; }); options.ListenAnyIP(5002, listenOptions => { listenOptions.UseHttps(StoreName.My, "localhost"); listenOptions.UseConnectionLogging(); listenOptions.Protocols = HttpProtocols.Http3; }); options.ListenAnyIP(5003, listenOptions => { listenOptions.UseHttps(httpsOptions => { // ConnectionContext is null httpsOptions.ServerCertificateSelector = (context, host) => cert; }); listenOptions.UseConnectionLogging(); listenOptions.Protocols = HttpProtocols.Http1AndHttp2AndHttp3; }); // No SslServerAuthenticationOptions callback is currently supported by QuicListener options.ListenAnyIP(5004, listenOptions => { listenOptions.UseHttps(httpsOptions => { httpsOptions.OnAuthenticate = (_, sslOptions) => sslOptions.ServerCertificate = cert; }); listenOptions.UseConnectionLogging(); listenOptions.Protocols = HttpProtocols.Http1AndHttp2; }); // ServerOptionsSelectionCallback isn't currently supported by QuicListener options.ListenAnyIP(5005, listenOptions => { ServerOptionsSelectionCallback callback = (SslStream stream, SslClientHelloInfo clientHelloInfo, object state, CancellationToken cancellationToken) => { var options = new SslServerAuthenticationOptions() { ServerCertificate = cert, }; return(new ValueTask <SslServerAuthenticationOptions>(options)); }; listenOptions.UseHttps(callback, state: null); listenOptions.Protocols = HttpProtocols.Http1AndHttp2; }); // TlsHandshakeCallbackOptions (ServerOptionsSelectionCallback) isn't currently supported by QuicListener options.ListenAnyIP(5006, listenOptions => { listenOptions.UseHttps(new TlsHandshakeCallbackOptions() { OnConnection = context => { var options = new SslServerAuthenticationOptions() { ServerCertificate = cert, }; return(new ValueTask <SslServerAuthenticationOptions>(options)); }, }); listenOptions.UseConnectionLogging(); listenOptions.Protocols = HttpProtocols.Http1AndHttp2; }); }) .UseStartup <Startup>(); }); hostBuilder.Build().Run(); }
public static Task Main(string[] args) { TaskScheduler.UnobservedTaskException += (sender, e) => { Console.WriteLine("Unobserved exception: {0}", e.Exception); }; var hostBuilder = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseKestrel((context, options) => { if (context.HostingEnvironment.IsDevelopment()) { ShowConfig(context.Configuration); } var basePort = context.Configuration.GetValue <int?>("BASE_PORT") ?? 5000; options.ConfigureHttpsDefaults(httpsOptions => { httpsOptions.SslProtocols = SslProtocols.Tls12; if (!OperatingSystem.IsMacOS()) { // Delayed client certificate negotiation is not supported on macOS. httpsOptions.ClientCertificateMode = ClientCertificateMode.DelayCertificate; } }); options.Listen(IPAddress.Loopback, basePort, listenOptions => { // Uncomment the following to enable Nagle's algorithm for this endpoint. //listenOptions.NoDelay = false; listenOptions.UseConnectionLogging(); }); options.Listen(IPAddress.Loopback, basePort + 1, listenOptions => { listenOptions.Protocols = Microsoft.AspNetCore.Server.Kestrel.Core.HttpProtocols.Http1; listenOptions.UseHttps(); listenOptions.UseConnectionLogging(); }); options.ListenLocalhost(basePort + 2, listenOptions => { // Use default dev cert listenOptions.UseHttps(); }); options.ListenAnyIP(basePort + 3); options.ListenAnyIP(basePort + 4, listenOptions => { listenOptions.UseHttps(StoreName.My, "localhost", allowInvalid: true); }); options.ListenAnyIP(basePort + 5, listenOptions => { var localhostCert = CertificateLoader.LoadFromStoreCert("localhost", "My", StoreLocation.CurrentUser, allowInvalid: true); listenOptions.UseHttps((stream, clientHelloInfo, state, cancellationToken) => { // Here you would check the name, select an appropriate cert, and provide a fallback or fail for null names. var serverName = clientHelloInfo.ServerName; if (serverName != null && serverName != "localhost") { throw new AuthenticationException($"The endpoint is not configured for server name '{clientHelloInfo.ServerName}'."); } return(new ValueTask <SslServerAuthenticationOptions>(new SslServerAuthenticationOptions { ServerCertificate = localhostCert })); }, state: null); }); options .Configure() .Endpoint(IPAddress.Loopback, basePort + 6) .LocalhostEndpoint(basePort + 7) .Load(); // reloadOnChange: true is the default options .Configure(context.Configuration.GetSection("Kestrel"), reloadOnChange: true) .Endpoint("NamedEndpoint", opt => { }) .Endpoint("NamedHttpsEndpoint", opt => { opt.HttpsOptions.SslProtocols = SslProtocols.Tls12; }); options.UseSystemd(); // The following section should be used to demo sockets //options.ListenUnixSocket("/tmp/kestrel-test.sock"); }) .UseContentRoot(Directory.GetCurrentDirectory()) .UseStartup <Startup>(); }) .ConfigureLogging((_, factory) => { factory.SetMinimumLevel(LogLevel.Debug); factory.AddConsole(); }) .ConfigureAppConfiguration((hostingContext, config) => { var env = hostingContext.HostingEnvironment; config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true); }); return(hostBuilder.Build().RunAsync()); }