public static void ConfigureEndpoints(this KestrelServerOptions options) { // Used for accessing certera locally _localCert = GenerateSelfSignedCertificate("localhost"); var configuration = options.ApplicationServices.GetRequiredService <IConfiguration>(); var httpServer = new HttpServer(); configuration.GetSection("HTTPServer").Bind(httpServer); // Configure HTTP on port 80 on any IP address options.ListenAnyIP(80); // Configure HTTPS on port 443 options.ListenAnyIP(443, listenOptions => { listenOptions.UseHttps(httpsOptions => { httpsOptions.ServerCertificateSelector = (ctx, name) => { // If we're here, it means we've already completed setup // and there should be a cert. // Try to get the cert and fallback to default localhost cert. // TODO: check for closure issues on "options" below return(GetHttpsCertificate(ctx, options, name)); }; }); }); }
private static void SetHttpsAndUrls(KestrelServerOptions kestrelOptions, IWireMockMiddlewareOptions wireMockMiddlewareOptions, IEnumerable <HostUrlDetails> urlDetails) { foreach (var urlDetail in urlDetails) { if (urlDetail.IsHttps) { kestrelOptions.ListenAnyIP(urlDetail.Port, listenOptions => { if (wireMockMiddlewareOptions.CustomCertificateDefined) { listenOptions.UseHttps(CertificateLoader.LoadCertificate( wireMockMiddlewareOptions.X509StoreName, wireMockMiddlewareOptions.X509StoreLocation, wireMockMiddlewareOptions.X509ThumbprintOrSubjectName, wireMockMiddlewareOptions.X509CertificateFilePath, wireMockMiddlewareOptions.X509CertificatePassword, urlDetail.Host) ); } else { listenOptions.UseHttps(); } }); } else { kestrelOptions.ListenAnyIP(urlDetail.Port); } } }
private static void ipConfig(KestrelServerOptions o) { var portStr = CmdHelper.QueryParameter("-p", "8080"); if (!int.TryParse(portStr, out int port)) { port = 9001; } var ip = CmdHelper.QueryParameter("-ip", "localhost"); Console.WriteLine(ip); if (ip.ToLower() == "any") { Console.WriteLine("ListenAnyIP"); o.ListenAnyIP(port); } else if (ip == "127.0.0.1" || ip.ToLower() == "localhost") { Console.WriteLine("ListenLocalhost"); o.ListenLocalhost(port); } else { Console.WriteLine("Listen"); o.Listen(System.Net.IPAddress.Parse(ip), port); } }
internal void ConfigureKestrel(KestrelServerOptions options) { options.AllowSynchronousIO = false; options.Limits.RequestHeadersTimeout = RequestHeadersTimeout; options.Limits.KeepAliveTimeout = KeepAliveTimeout; options.ListenAnyIP(Port, ConfigureListener); }
public void LogsInformationWhenKestrelAddressesAreOverridden() { var logger = new TestApplicationErrorLogger(); var overriddenAddress = "http://localhost:5000"; var addresses = new ServerAddressesFeature(); addresses.InternalCollection.Add(overriddenAddress); var options = new KestrelServerOptions(); options.ListenAnyIP(8080); var addressBindContext = TestContextFactory.CreateAddressBindContext( addresses, options, logger, endpoint => Task.CompletedTask); addressBindContext.ServerAddressesFeature.PreferHostingUrls = true; var bindTask = AddressBinder.BindAsync(options.ListenOptions, addressBindContext, CancellationToken.None); Assert.True(bindTask.IsCompletedSuccessfully); var log = Assert.Single(logger.Messages); Assert.Equal(LogLevel.Information, log.LogLevel); Assert.Equal(CoreStrings.FormatOverridingWithPreferHostingUrls(nameof(addressBindContext.ServerAddressesFeature.PreferHostingUrls), overriddenAddress), log.Message); }
public static async Task Main(string[] args) { shutdown = new ManualResetEventSlim(); Console.CancelKeyPress += Console_CancelKeyPress; var options = new KestrelServerOptions(); options.ListenAnyIP(5000, c => { c.UseHttpApplication <Application>(); }); var server = new KestrelServer( Options.Create(options), new SocketTransportFactory( Options.Create(new SocketTransportOptions()), NullLoggerFactory.Instance), NullLoggerFactory.Instance); var application = new HostingApplication((context) => Task.CompletedTask, new DefaultHttpContextFactory(new ServiceProvider())); await server.StartAsync(application, CancellationToken.None); Console.WriteLine("Application started."); shutdown.Wait(); Console.WriteLine("Shutting down..."); server.Dispose(); await server.StopAsync(CancellationToken.None); }
public void ConfigureEndpointDefaultsAppliesToNewEndpoints() { var options = new KestrelServerOptions(); options.ListenLocalhost(5000); Assert.True(options.ListenOptions[0].NoDelay); options.ConfigureEndpointDefaults(opt => { opt.NoDelay = false; }); options.Listen(new IPEndPoint(IPAddress.Loopback, 5000), opt => { // ConfigureEndpointDefaults runs before this callback Assert.False(opt.NoDelay); }); Assert.False(options.ListenOptions[1].NoDelay); options.ListenLocalhost(5000, opt => { Assert.False(opt.NoDelay); opt.NoDelay = true; // Can be overriden }); Assert.True(options.ListenOptions[2].NoDelay); options.ListenAnyIP(5000, opt => { Assert.False(opt.NoDelay); }); Assert.False(options.ListenOptions[3].NoDelay); }
public void ConfigureEndpointDefaultsAppliesToNewEndpoints() { var options = new KestrelServerOptions(); options.ListenLocalhost(5000); Assert.Equal(HttpProtocols.Http1AndHttp2, options.CodeBackedListenOptions[0].Protocols); options.ConfigureEndpointDefaults(opt => { opt.Protocols = HttpProtocols.Http1; }); options.Listen(new IPEndPoint(IPAddress.Loopback, 5000), opt => { // ConfigureEndpointDefaults runs before this callback Assert.Equal(HttpProtocols.Http1, opt.Protocols); }); Assert.Equal(HttpProtocols.Http1, options.CodeBackedListenOptions[1].Protocols); options.ListenLocalhost(5000, opt => { Assert.Equal(HttpProtocols.Http1, opt.Protocols); opt.Protocols = HttpProtocols.Http2; // Can be overriden }); Assert.Equal(HttpProtocols.Http2, options.CodeBackedListenOptions[2].Protocols); options.ListenAnyIP(5000, opt => { opt.Protocols = HttpProtocols.Http2; }); Assert.Equal(HttpProtocols.Http2, options.CodeBackedListenOptions[3].Protocols); }
/// <summary> /// Получить настройки HTTP для кроссплатформенного веб-сервер для ASP.NET Core. /// </summary> /// <param name="options">Обеспечивает программную настройку специфичных для Kestrel функций.</param> private static void KestrelHttpOptions(KestrelServerOptions options) { try { int httpPort = GetHttpPort(); options.ListenAnyIP(httpPort); } catch (Exception e) { Console.WriteLine(e.Message); } }
private static void AddKestrelServerOptions(WebHostBuilderContext builderContext, KestrelServerOptions options) { var tcpListenPort = 9900; options.ListenAnyIP(tcpListenPort, builder => { builder.UseConnectionHandler <MyEchoConnectionHandler>(); }); // Configure Kestrel from appsettings.json. var kestrelConfig = builderContext.Configuration.GetSection("Kestrel"); options.Configure(kestrelConfig); }
/// <summary> /// Получить настройки HTTPS для кроссплатформенного веб-сервер для ASP.NET Core. /// </summary> /// <param name="options">Обеспечивает программную настройку специфичных для Kestrel функций.</param> private static void KestrelHttpsOptions(KestrelServerOptions options) { try { int httpPort = GetHttpsPort(); (string path, string password) = GetHttpsSertificate(); options.ListenAnyIP(httpPort, listenOptions => { listenOptions.UseHttps(path, password); }); } catch (Exception e) { Console.WriteLine(e.Message); } }
private static void SetupKestrel(WebHostBuilderContext ctx, KestrelServerOptions options) { const int defaultPort = 443; var servicePort = ctx.Configuration.GetValue("servicePort", 4444); options.ListenAnyIP(servicePort, listenOptions => { listenOptions.Protocols = HttpProtocols.Http2; if (servicePort == defaultPort) { listenOptions.UseHttps("calculatorCert.pfx", "calc123"); } }); }
/// <summary> /// Configure the <see cref="KestrelServerOptions"/> with the specified URL. /// </summary> private bool Listen(KestrelServerOptions options, string url) { BindingAddress address = null; try { address = BindingAddress.Parse(url); } catch (Exception ex) { // Record the exception; it will be logged later through ILogger. Errors.Add(new AddressListenResult(url, ex)); return(false); } Action <ListenOptions> configureListenOptions = (listenOptions) => { if (address.Scheme.Equals(Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase)) { listenOptions.UseHttps(); } }; try { if (address.Host.Equals("localhost", StringComparison.OrdinalIgnoreCase)) { options.ListenLocalhost(address.Port, configureListenOptions); } else if (IPAddress.TryParse(address.Host, out IPAddress ipAddress)) { options.Listen(ipAddress, address.Port, configureListenOptions); } else { options.ListenAnyIP(address.Port, configureListenOptions); } } catch (InvalidOperationException ex) { // This binding failure is typically due to missing default certificate. // Record the exception; it will be logged later through ILogger. Errors.Add(new AddressListenResult(url, ex)); return(false); } return(true); }
/// <summary> /// Configures AirDrop defaults for Kestrel. /// </summary> /// <param name="options">A <see cref="KestrelServerOptions"/> instance to configure.</param> /// <param name="cert">An <see cref="X509Certificate2"/> representing the certificate to use for the AirDrop HTTPS endpoint.</param> public static void ConfigureAirDropDefaults(this KestrelServerOptions options, X509Certificate2 cert) { if (cert == null) { throw new ArgumentNullException(nameof(cert)); } var airDropOptions = options.ApplicationServices.GetRequiredService <IOptions <AirDropOptions> >(); options.ConfigureEndpointDefaults( endpointDefaults => { endpointDefaults.UseHttps(cert); }); options.ListenAnyIP(airDropOptions.Value.ListenPort); }
public static void UseSslAuth(this KestrelServerOptions options) { var serviceProvider = options.ApplicationServices; var kvClient = serviceProvider.GetRequiredService <IKeyVaultClient>(); var configuration = serviceProvider.GetRequiredService <IConfiguration>(); var httpsSettings = configuration.GetConfiguredSettings <HttpsSettings>(); if (httpsSettings != null) { Console.WriteLine( $"serving web request... port: {httpsSettings.PortNumber}, cert: {httpsSettings.SslCertSecretName}"); var vaultSettings = configuration.GetConfiguredSettings <VaultSettings>(); var x509 = kvClient.GetX509CertificateAsync(vaultSettings.VaultUrl, httpsSettings.SslCertSecretName) .GetAwaiter().GetResult(); options.ListenAnyIP(httpsSettings.PortNumber, listenOptions => { listenOptions.UseHttps(x509); }); } }
public async Task ListenIPWithEphemeralPort_TransportsGetIPv6Any() { var options = new KestrelServerOptions(); options.ApplicationServices = new ServiceCollection() .AddLogging() .BuildServiceProvider(); options.ListenAnyIP(0, options => { options.UseHttps(TestResources.GetTestCertificate()); options.Protocols = HttpProtocols.Http1AndHttp2AndHttp3; }); var mockTransportFactory = new MockTransportFactory(); var mockMultiplexedTransportFactory = new MockMultiplexedTransportFactory(); using var server = new KestrelServerImpl( Options.Create(options), new List <IConnectionListenerFactory>() { mockTransportFactory }, new List <IMultiplexedConnectionListenerFactory>() { mockMultiplexedTransportFactory }, new LoggerFactory(new[] { new KestrelTestLoggerProvider() })); await server.StartAsync(new DummyApplication(context => Task.CompletedTask), CancellationToken.None); var transportEndPoint = Assert.Single(mockTransportFactory.BoundEndPoints); var multiplexedTransportEndPoint = Assert.Single(mockMultiplexedTransportFactory.BoundEndPoints); Assert.Equal(IPAddress.IPv6Any, ((IPEndPoint)transportEndPoint.OriginalEndPoint).Address); Assert.Equal(IPAddress.IPv6Any, ((IPEndPoint)multiplexedTransportEndPoint.OriginalEndPoint).Address); // Should have been assigned a random value. Assert.NotEqual(0, ((IPEndPoint)transportEndPoint.BoundEndPoint).Port); // Same random value should be used for both transports. Assert.Equal(((IPEndPoint)transportEndPoint.BoundEndPoint).Port, ((IPEndPoint)multiplexedTransportEndPoint.BoundEndPoint).Port); }
static async Task Main(string[] args) { var serverOptions = new KestrelServerOptions(); serverOptions.ListenAnyIP(8080); var transportOptions = new SocketTransportOptions(); var loggerFactory = new NullLoggerFactory(); var applicationLifetime = new ApplicationLifetime(); var transportFactory = new SocketTransportFactory( new OptionsWrapper <SocketTransportOptions>(transportOptions), applicationLifetime, loggerFactory); using (var server = new KestrelServer(new OptionsWrapper <KestrelServerOptions>(serverOptions), transportFactory, loggerFactory)) { await server.StartAsync(new Application(), CancellationToken.None); Console.ReadLine(); } }
private static void ConfigKestrel(KestrelServerOptions kestrelOpt) { kestrelOpt.ListenAnyIP(5001, ConfigureListen); }
static void ServerConfigure(int port, KestrelServerOptions opt) { opt.ListenAnyIP(port); }
/// <summary> /// Configure Kestrel to use Certificate-based Authentication /// </summary> /// <param name="options"></param> private static void ConfigureKestrelCertAuth(KestrelServerOptions options) { using var scope = options.ApplicationServices.CreateScope(); var logger = scope.ServiceProvider .GetService <ILoggerFactory>() ?.CreateLogger(nameof(Program)); var settings = scope.ServiceProvider .GetService <IOptionsMonitor <KestrelAuthenticationConfiguration> >() ?.CurrentValue; if (settings is null) { logger.LogWarning($"{nameof(KestrelAuthenticationConfiguration)} is null, can't configure kestrel"); return; } if (!settings.Enabled) { logger.LogWarning("skipping configuration of kestrel"); return; } if (string.IsNullOrWhiteSpace(settings.Certificate)) { logger.LogError("no certificate given, provide path to a valid certificate with '" + $"{nameof(KestrelAuthenticationConfiguration)}:{nameof(KestrelAuthenticationConfiguration.Certificate)}'"); return; } X509Certificate2 certificate = null; if (Path.GetExtension(settings.Certificate) == "pfx") { certificate = settings.Password is null ? new X509Certificate2(settings.Certificate) : new X509Certificate2(settings.Certificate, settings.Password); } var certpath = Environment.GetEnvironmentVariable("ASPNETCORE_SSLCERT_PATH"); if (!string.IsNullOrEmpty(certpath) || Path.GetExtension(settings.Certificate) == "crt") { var port = Environment.GetEnvironmentVariable("ASPNETCORE_SSL_PORT"); certificate = X509CertificateUtility.LoadFromCrt(certpath) ?? X509CertificateUtility.LoadFromCrt(settings.Certificate); settings.Port = int.Parse(port ?? settings.Port.ToString()); } var connectionOptions = new HttpsConnectionAdapterOptions { ServerCertificate = certificate }; var inDocker = bool.Parse(Environment.GetEnvironmentVariable("DOTNET_RUNNING_IN_CONTAINER") ?? "false"); if (!inDocker) { logger.LogInformation("Not running in docker, adding client certificate validation"); connectionOptions.ClientCertificateMode = ClientCertificateMode.RequireCertificate; connectionOptions.ClientCertificateValidation = CertificateValidator.DisableChannelValidation; } logger.LogInformation($"loaded certificate: {connectionOptions.ServerCertificate}"); if (string.IsNullOrWhiteSpace(settings.IpAddress)) { logger.LogError("no ip-address given, provide a valid ipv4 or ipv6 binding-address or 'localhost' for '" + $"{nameof(KestrelAuthenticationConfiguration)}:{nameof(KestrelAuthenticationConfiguration.IpAddress)}'"); return; } if (settings.IpAddress == "localhost") { logger.LogInformation($"binding to: https://localhost:{settings.Port}"); options.ListenLocalhost(settings.Port, listenOptions => { listenOptions.UseHttps(connectionOptions); }); } else if (settings.IpAddress == "*") { logger.LogInformation($"binding to: https://*:{settings.Port}"); options.ListenAnyIP(settings.Port, listenOptions => { listenOptions.UseHttps(connectionOptions); }); } else { var ip = IPAddress.Parse(settings.IpAddress); logger.LogInformation($"binding to: https://{ip}:{settings.Port}"); options.Listen(ip, settings.Port, listenOptions => { listenOptions.UseHttps(connectionOptions); }); } }
public void ConfigureKestrelServerOptions(KestrelServerOptions opt, object?sslCertSelectorParam) { opt.AddServerHeader = !this.HideKestrelServerHeader; KestrelServerWithStackOptions?withStackOpt = opt as KestrelServerWithStackOptions; if (this.LocalHostOnly) { foreach (int port in this.HttpPortsList) { opt.ListenLocalhost(port); } foreach (int port in this.HttpsPortsList) { opt.ListenLocalhost(port, lo => EnableHttps(lo)); } } else if (this.IPv4Only) { foreach (int port in this.HttpPortsList) { opt.Listen(IPAddress.Any, port); } foreach (int port in this.HttpsPortsList) { opt.Listen(IPAddress.Any, port, lo => EnableHttps(lo)); } } else { foreach (int port in this.HttpPortsList) { opt.ListenAnyIP(port); } foreach (int port in this.HttpsPortsList) { opt.ListenAnyIP(port, lo => EnableHttps(lo)); } } opt.Limits.MaxRequestBodySize = this.MaxRequestBodySize; if (withStackOpt != null) { // Kestrel with Stack withStackOpt.TcpIp = this.TcpIp ?? LocalNet; } void EnableHttps(ListenOptions listenOptions) { listenOptions.UseHttps(httpsOptions => { httpsOptions.SslProtocols = SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12; bool useGlobalCertVault = false; #if CORES_BASIC_JSON #if CORES_BASIC_SECURITY useGlobalCertVault = this.UseGlobalCertVault; #endif // CORES_BASIC_JSON #endif // CORES_BASIC_SECURITY; if (useGlobalCertVault == false) { if (this.ServerCertSelector != null) { httpsOptions.ServerCertificateSelector = ((ctx, sni) => this.ServerCertSelector(sslCertSelectorParam, sni)); } } #if CORES_BASIC_JSON #if CORES_BASIC_SECURITY if (useGlobalCertVault) { if (this.GlobalCertVaultDefauleCert != null) { GlobalCertVault.SetDefaultCertificate(this.GlobalCertVaultDefauleCert); } httpsOptions.ServerCertificateSelector = ((ctx, sni) => (X509Certificate2)GlobalCertVault.GetGlobalCertVault().X509CertificateSelector(sni, !this.HasHttpPort80).NativeCertificate); } #endif // CORES_BASIC_JSON #endif // CORES_BASIC_SECURITY; }); } }
internal void ConfigureKestrel(KestrelServerOptions options) => options.ListenAnyIP(Port, ConfigureListener);
private static void ConfigureKestrel(WebHostBuilderContext context, KestrelServerOptions options) { options.ListenAnyIP(Startup.Port); }