/// <summary> /// Using of Forwarded Headers, Hsts, XXssProtection and Csp /// </summary> /// <param name="app"></param> /// <param name="configuration"></param> public static void UseSecurityHeaders(this IApplicationBuilder app, IConfiguration configuration) { var forwardingOptions = new ForwardedHeadersOptions() { ForwardedHeaders = ForwardedHeaders.All }; forwardingOptions.KnownNetworks.Clear(); forwardingOptions.KnownProxies.Clear(); app.UseForwardedHeaders(forwardingOptions); app.UseXXssProtection(options => options.EnabledWithBlockMode()); app.UseXContentTypeOptions(); app.UseXfo(options => options.SameOrigin()); app.UseReferrerPolicy(options => options.NoReferrer()); // CSP Configuration to be able to use external resources var cspTrustedDomains = new List <string>(); configuration.GetSection(ConfigurationConsts.CspTrustedDomainsKey).Bind(cspTrustedDomains); if (cspTrustedDomains.Any()) { app.UseCsp(csp => { csp.ImageSources(options => { options.SelfSrc = true; options.CustomSources = cspTrustedDomains; options.Enabled = true; }); csp.FontSources(options => { options.SelfSrc = true; options.CustomSources = cspTrustedDomains; options.Enabled = true; }); csp.ScriptSources(options => { options.SelfSrc = true; options.CustomSources = cspTrustedDomains; options.Enabled = true; options.UnsafeInlineSrc = true; options.UnsafeEvalSrc = true; }); csp.StyleSources(options => { options.SelfSrc = true; options.CustomSources = cspTrustedDomains; options.Enabled = true; options.UnsafeInlineSrc = true; }); csp.DefaultSources(options => { options.SelfSrc = true; options.CustomSources = cspTrustedDomains; options.Enabled = true; }); }); } }
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { // app.AddCustomSecurityHeaders(); if (env.IsDevelopment()) { app.AddDevMiddlewares(); } else { app.UseHsts(); app.UseResponseCompression(); } app.AddCustomLocalization(); app.UseHttpsRedirection(); // https://github.com/openiddict/openiddict-core/issues/518 // And // https://github.com/aspnet/Docs/issues/2384#issuecomment-297980490 var forwarOptions = new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto }; forwarOptions.KnownNetworks.Clear(); forwarOptions.KnownProxies.Clear(); app.UseForwardedHeaders(forwarOptions); app.UseAuthentication(); app.UseStaticFiles(); app.UseSpaStaticFiles(); app.UseCookiePolicy(); app.UseSignalR(routes => { routes.MapHub <Chat>("/chathub"); routes.MapHub <ShapeHub>("/shapeHub"); }); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller}/{action=Index}/{id?}"); // http://stackoverflow.com/questions/25982095/using-googleoauth2authenticationoptions-got-a-redirect-uri-mismatch-error // routes.MapRoute(name: "signin-google", template: "signin-google", defaults: new { controller = "Account", action = "ExternalLoginCallback" }); routes.MapRoute(name: "set-language", template: "setlanguage", defaults: new { controller = "Home", action = "SetLanguage" }); }); app.UseSpa(spa => { spa.Options.SourcePath = "ClientApp"; /* * // If you want to enable server-side rendering (SSR), * // [1] In AspNetCoreSpa.csproj, change the <BuildServerSideRenderer> property * // value to 'true', so that the SSR bundle is built during publish * // [2] Uncomment this code block */ // spa.UseSpaPrerendering(options => // { // options.BootModulePath = $"{spa.Options.SourcePath}/dist-server/main.bundle.js"; // options.BootModuleBuilder = env.IsDevelopment() ? new AngularCliBuilder(npmScript: "build:ssr") : null; // options.ExcludeUrls = new[] { "/sockjs-node" }; // options.SupplyData = (requestContext, obj) => // { // // var result = appService.GetApplicationData(requestContext).GetAwaiter().GetResult(); // obj.Add("Cookies", requestContext.Request.Cookies); // }; // }); if (env.IsDevelopment()) { spa.UseAngularCliServer(npmScript: "start"); // OR //spa.UseProxyToSpaDevelopmentServer("http://localhost:4200"); } }); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseMigrationsEndPoint(); } 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.UseCors(); var fordwardedHeaderOptions = new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto }; fordwardedHeaderOptions.KnownNetworks.Clear(); fordwardedHeaderOptions.KnownProxies.Clear(); app.UseForwardedHeaders(fordwardedHeaderOptions); app.UseHealthChecks("/health"); app.UseHttpsRedirection(); app.UseDefaultFiles(); app.UseStaticFiles(); if (!env.IsDevelopment()) { app.UseSpaStaticFiles(); } app.UseSwaggerUi3(settings => { settings.Path = "/api"; settings.DocumentPath = "/api/specification.json"; }); app.UseRouting(); app.UseAuthentication(); app.UseIdentityServer(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller}/{action=Index}/{id?}"); endpoints.MapRazorPages(); }); app.UseSpa(spa => { // To learn more about options for serving an Angular SPA from ASP.NET Core, // see https://go.microsoft.com/fwlink/?linkid=864501 spa.Options.SourcePath = "ClientApp"; if (env.IsDevelopment()) { spa.UseReactDevelopmentServer(npmScript: "start"); } }); }
/// <summary> /// Sets up the proxy configuration based on the addresses in <paramref name="allowedProxies"/>. /// </summary> /// <param name="config">The <see cref="NetworkConfiguration"/> containing the config settings.</param> /// <param name="allowedProxies">The string array to parse.</param> /// <param name="options">The <see cref="ForwardedHeadersOptions"/> instance.</param> internal static void AddProxyAddresses(NetworkConfiguration config, string[] allowedProxies, ForwardedHeadersOptions options) { for (var i = 0; i < allowedProxies.Length; i++) { if (IPNetAddress.TryParse(allowedProxies[i], out var addr)) { AddIpAddress(config, options, addr.Address, addr.PrefixLength); } else if (IPHost.TryParse(allowedProxies[i], out var host)) { foreach (var address in host.GetAddresses()) { AddIpAddress(config, options, addr.Address, addr.PrefixLength); } } } }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app) { app.Use(async(context, next) => { context.Request.Scheme = "https"; await next(); }); if (_env.IsDevelopment()) { IdentityModelEventSource.ShowPII = true; app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/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(); var forwardOptions = new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.All }; forwardOptions.KnownNetworks.Clear(); forwardOptions.KnownProxies.Clear(); app.UseForwardedHeaders(forwardOptions); app.UseRouting(); app.UseVersioningEndpoint(); app.UseHealthChecks("/health"); app.UseSession(); var enableSessionLogging = _configuration.GetValue <bool>("EnableSessionLogging"); if (enableSessionLogging) { app.Use(async(context, next) => { var sessionId = context.Session.Id; var keys = context.Session.Keys; var sessionKeys = keys.Count() > 0 ? string.Join(", ", keys) : "empty"; var logger = context.RequestServices.GetService <ILogger <Startup> >(); logger.LogInformation($"Incoming request with session Id: {sessionId} and session keys: {sessionKeys}."); await next(); }); } app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=BreathingSpace}/{action=Index}/{id?}"); }); }
public ForwardedForOperationFilter(IOptions <ForwardedHeadersOptions> forwardedHeadersOptions) { _forwardedHeadersOptions = forwardedHeadersOptions.Value; }
/// <summary> /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. /// </summary> /// <param name="app"></param> /// <param name="env"></param> public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } var options = new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedHost | ForwardedHeaders.XForwardedProto }; options.KnownNetworks.Clear(); options.KnownProxies.Clear(); app.UseForwardedHeaders(options); app.Use((context, next) => { if (!context.Request.Headers.TryGetValue("X-Forwarded-PathBase", out var pathBases)) { return(next()); } context.Request.PathBase = pathBases.First(); if (context.Request.PathBase.Value.EndsWith("/")) { context.Request.PathBase = context.Request.PathBase.Value.Substring(0, context.Request.PathBase.Value.Length - 1); } // ReSharper disable once InvertIf if (context.Request.Path.Value.StartsWith(context.Request.PathBase.Value)) { var after = context.Request.Path.Value.Substring( context.Request.PathBase.Value.Length, context.Request.Path.Value.Length - context.Request.PathBase.Value.Length); context.Request.Path = after; } return(next()); }); app.UseOpenApi(settings => { settings.PostProcess = (document, req) => { document.Info.Version = "v1"; document.Info.Title = "Bike Data Project - Geo API"; document.Info.Description = "An API allowing for the logging of GPS data.."; document.Info.TermsOfService = string.Empty; document.Info.Contact = new NSwag.OpenApiContact() { Name = "Open Knowledge Belgium VZW/ASBL", Email = "*****@*****.**", Url = "https://www.bikedataproject.info" }; }; }); app.UseSwaggerUi3(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }