public void Configure( IApplicationBuilder app, ApplicationDbContext context) { context.Database.Migrate(); ForwardedHeadersOptions forwardedHeadersOptions = new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto }; forwardedHeadersOptions.KnownNetworks.Clear(); forwardedHeadersOptions.KnownProxies.Clear(); app.UseForwardedHeaders(forwardedHeadersOptions); InitializeDatabase(app); if (Environment.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); HstsBuilderExtensions.UseHsts(app); } FileExtensionContentTypeProvider fileExtensionContentTypeProvider = new FileExtensionContentTypeProvider(); fileExtensionContentTypeProvider.Mappings[".webmanifest"] = "application/manifest+json"; app.UseStaticFiles(new StaticFileOptions() { ContentTypeProvider = fileExtensionContentTypeProvider }); app.UseCsp(csp => { csp.AllowFonts .FromSelf() .From("fonts.googleapis.com") .From("fonts.gstatic.com"); }); app.UseHttpsRedirection(); app.UseRouting(); app.UseIdentityServer(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}"); }); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (HostingEnvironmentExtensions.IsDevelopment(env)) { DeveloperExceptionPageExtensions.UseDeveloperExceptionPage(app); } else { HstsBuilderExtensions.UseHsts(app); } MvcApplicationBuilderExtensions.UseMvc(app); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (HostingEnvironmentExtensions.IsDevelopment(env)) { DeveloperExceptionPageExtensions.UseDeveloperExceptionPage(app); } else { ExceptionHandlerExtensions.UseExceptionHandler(app, "/Error"); HstsBuilderExtensions.UseHsts(app); } HttpsPolicyBuilderExtensions.UseHttpsRedirection(app); StaticFileExtensions.UseStaticFiles(app); MvcApplicationBuilderExtensions.UseMvc(app); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, UserManager <ApplicationUser> userManager, ApplicationDbContext context) { //https://stackoverflow.com/questions/52954158/asp-net-core-2-1-no-http-https-redirection-in-app-engine app.UseForwardedHeaders(); app.Use(async(context, next) => { if (context.Request.IsHttps || context.Request.Headers["X-Forwarded-Proto"] == Uri.UriSchemeHttps) { await next(); } else { string queryString = context.Request.QueryString.HasValue ? context.Request.QueryString.Value : string.Empty; var https = "https://" + context.Request.Host + context.Request.Path + queryString; context.Response.Redirect(https); } }); if (env.IsDevelopment()) { // These will run synchronously var pass = Configuration.GetSection("Passwords").GetSection("adminpass").Value; SeedData.SeedApplicationUsers(userManager, "*****@*****.**", "alpha", pass); SeedData.SeedApplicationUsers(userManager, "*****@*****.**", "beta", pass); SeedData.SeedApplicationUsers(userManager, "*****@*****.**", "gamma", pass); SeedData.SeedApplicationRooms(context, userManager); SeedData.SeedApplicationPosts(context, userManager, Configuration.GetConnectionString("test")); app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); } else { app.UseStatusCodePagesWithRedirects("/Error/{0}"); 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. HstsBuilderExtensions.UseHsts(app); app.UseCsp(csp => { csp.AllowScripts .FromSelf() .From("https://kit.fontawesome.com"); csp.AllowStyles .FromSelf() .From("kit-free.fontawesome.com/releases/latest/css/"); csp.OnSendingHeader = context => { context.ShouldNotSend = context.HttpContext.Request.Path.StartsWithSegments("/Identity"); return(Task.CompletedTask); }; }); } // app.ConfigureExceptionHandler(); app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); endpoints.MapRazorPages(); endpoints.MapHub <ChatHub>("/hub"); }); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { //添加文件日志 loggerFactory.AddFile(Configuration.GetSection("FileLogging")); //配置FluentValidation的本地化 app.ConfigLocalizationFluentValidation(); //注册管道是有顺序的 if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); } else { app.UseExceptionHandler("/Home/Error"); } //检查到相应配置启用https跳转 if (Configuration.GetValue("UseHttpsRedirection", false) && (Configuration.GetSection("RafHost").GetSection("Endpoints").GetSection("Https") .GetValue("IsEnabled", false) || Environment.IsDevelopment())) { //app.UseHsts(); HstsBuilderExtensions.UseHsts(app); //注册强制Https跳转到管道 app.UseHttpsRedirection(); } //注册响应压缩到管道 app.UseResponseCompression(); //注册内容安全策略到管道 // Content Security Policy app.UseCsp(csp => { // If nothing is mentioned for a resource class, allow from this domain csp.ByDefaultAllow .FromSelf(); // Allow JavaScript from: csp.AllowScripts .FromSelf() //This domain .AllowUnsafeInline() .AllowUnsafeEval() .From("localhost:5000") //These two domains .From("localhost:5001") .From("localhost:5002") .From("localhost:5003") .From("localhost:5004") .From("localhost:5005") .From("ajax.aspnetcdn.com") .From("cdnjs.cloudflare.com"); //.AddNonce();//此项与AllowUnsafeInline冲突,会被AllowUnsafeInline选项覆盖 // CSS allowed from: csp.AllowStyles .FromSelf() .AllowUnsafeInline() .From("localhost:5000") //These two domains .From("localhost:5001") .From("localhost:5002") .From("localhost:5003") .From("localhost:5004") .From("localhost:5005") .From("ajax.aspnetcdn.com") .From("fonts.googleapis.com") .From("cdnjs.cloudflare.com"); //.AddNonce();//此项与AllowUnsafeInline冲突,会被AllowUnsafeInline选项覆盖 csp.AllowImages .FromSelf() .DataScheme() .From("localhost:5000") //These two domains .From("localhost:5001") .From("localhost:5002") .From("localhost:5003") .From("localhost:5004") .From("localhost:5005") .From("ajax.aspnetcdn.com"); // HTML5 audio and video elemented sources can be from: csp.AllowAudioAndVideo .FromNowhere(); //Nowhere, no media allowed // Contained iframes can be sourced from: csp.AllowFrames .FromSelf(); // Allow AJAX, WebSocket and EventSource connections to: csp.AllowConnections .ToSelf() .To("ws://localhost:5000") .To("wss://localhost:5001") ; // Allow fonts to be downloaded from: csp.AllowFonts .FromSelf() .From("fonts.gstatic.com") .From("ajax.aspnetcdn.com"); // Allow object, embed, and applet sources from: csp.AllowPlugins .FromNowhere(); // Allow other sites to put this in an iframe? csp.AllowFraming .FromAnywhere(); // Block framing on other sites, equivalent to X-Frame-Options: DENY if (env.IsDevelopment()) { // Do not block violations, only report // This is a good idea while testing your CSP // Remove it when you know everything will work //csp.SetReportOnly(); // Where should the violation reports be sent to? //csp.ReportViolationsTo("/csp-report"); } // Do not include the CSP header for requests to the /api endpoints //csp.OnSendingHeader = context => //{ // context.ShouldNotSend = context.HttpContext.Request.Path.StartsWithSegments("/api"); // return Task.CompletedTask; //}; }); //注册请求本地化到管道 var locOptions = app.ApplicationServices.GetService <IOptions <RequestLocalizationOptions> >(); app.UseRequestLocalization(locOptions.Value); //注册默认404页面到管道 app.UseStatusCodePages(async context => { if (context.HttpContext.Response.StatusCode != (int)HttpStatusCode.NotFound) { return; } PathString pathString = "/Home/NotFound"; QueryString queryString = new QueryString(); PathString originalPath = context.HttpContext.Request.Path; QueryString originalQueryString = context.HttpContext.Request.QueryString; context.HttpContext.Features.Set <IStatusCodeReExecuteFeature>(new StatusCodeReExecuteFeature() { OriginalPathBase = context.HttpContext.Request.PathBase.Value, OriginalPath = originalPath.Value, OriginalQueryString = (originalQueryString.HasValue ? originalQueryString.Value : null) }); context.HttpContext.Request.Path = pathString; context.HttpContext.Request.QueryString = queryString; try { await context.Next(context.HttpContext); } finally { context.HttpContext.Request.QueryString = originalQueryString; context.HttpContext.Request.Path = originalPath; context.HttpContext.Features.Set <IStatusCodeReExecuteFeature>(null); } }); //注册开发环境文件浏览器 if (Environment.IsDevelopment()) { var dir = new DirectoryBrowserOptions(); dir.FileProvider = new PhysicalFileProvider(Environment.ContentRootPath); dir.RequestPath = "/dir"; app.UseDirectoryBrowser(dir); var contentTypeProvider = new FileExtensionContentTypeProvider(); contentTypeProvider.Mappings.Add(".log", "text/plain"); var devStaticFileOptions = new StaticFileOptions { FileProvider = new PhysicalFileProvider(Environment.ContentRootPath), RequestPath = "/dir", ServeUnknownFileTypes = true, DefaultContentType = "application/octet-stream", ContentTypeProvider = contentTypeProvider }; app.UseStaticFiles(devStaticFileOptions); } //注册开发环境的npm和bower资源 if (Environment.IsDevelopment()) { var npmContentTypeProvider = new FileExtensionContentTypeProvider(); var npmStaticFileOptions = new StaticFileOptions { FileProvider = new PhysicalFileProvider(Environment.ContentRootPath + "/node_modules"), RequestPath = "/npm", ServeUnknownFileTypes = false, ContentTypeProvider = npmContentTypeProvider }; app.UseStaticFiles(npmStaticFileOptions); var bowerContentTypeProvider = new FileExtensionContentTypeProvider(); var bowerStaticFileOptions = new StaticFileOptions { FileProvider = new PhysicalFileProvider(Environment.ContentRootPath + "/bower_components"), RequestPath = "/bower", ServeUnknownFileTypes = false, ContentTypeProvider = bowerContentTypeProvider }; app.UseStaticFiles(bowerStaticFileOptions); } //注册静态文件到管道(wwwroot文件夹) app.UseStaticFiles(); //注册Cookie策略到管道(GDPR) app.UseCookiePolicy(); //注册跨域策略到管道 app.UseCors("CorsPolicy"); //注册IdentityServer4到管道 app.UseIdentityServer(); //注册SignalR到管道 app.UseSignalR(routes => { routes.MapHub <ChatHub>("/chatHub"); }); //注册MVC到管道 app.UseMvc(routes => { routes .MapRoute( name: "area", template: "{area:exists}/{controller=Home}/{action=Index}/{id?}" ) .MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseHealthChecks("/health"); var forwardedHeadersOptions = new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.All, RequireHeaderSymmetry = false, ForwardLimit = 10 }; foreach (var address in Configuration.GetSection("AllowedProxyIPs").Get <List <string> >() .Select(IPAddress.Parse)) { forwardedHeadersOptions.KnownProxies.Add(address); } foreach (var network in Configuration.GetSection("AllowedProxyNetworks").Get <List <string> >().Select(i => new IPNetwork(IPAddress.Parse(i.Substring(0, i.LastIndexOf("/", StringComparison.Ordinal))), int.Parse(i.Substring(i.LastIndexOf("/", StringComparison.Ordinal) + 1))) )) { forwardedHeadersOptions.KnownNetworks.Add(network); } app.UseForwardedHeaders(forwardedHeadersOptions); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseExceptionDemystifier(); } else { app.UseExceptionHandler("/Home/Error"); HstsBuilderExtensions.UseHsts(app); } app.UseHttpsRedirection(); app.UseRequestLocalization(new RequestLocalizationOptions { DefaultRequestCulture = new RequestCulture("en"), SupportedCultures = CultureInfo.GetCultures(CultureTypes.AllCultures), SupportedUICultures = new[] { new CultureInfo("en"), new CultureInfo("cs") } }); app.UseStaticFiles(); app.UseCookiePolicy(); app.UseAuthentication(); app.UseHangfireDashboard(options: new DashboardOptions { Authorization = new[] { new PermissionDashboardAuthorizationFilter() } }); app.UseHangfireServer(); app.UseMvc(routes => { routes.MapRoute( "areaRoute", "{area:exists}/{controller=Home}/{action=Index}/{id?}"); routes.MapRoute( "default", "{controller=Home}/{action=Index}/{id?}"); }); app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); }); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app) { if (RuntimeEnvironment.IsDevelopment() || RuntimeEnvironment.EnvironmentName.Equals("Local", StringComparison.InvariantCultureIgnoreCase)) { app.UseDeveloperExceptionPage(); } else { app.UseForwardedHeaders(); app.UseExceptionHandler("/Error"); if (UseHsts()) { Console.WriteLine("Using HSTS"); HstsBuilderExtensions.UseHsts(app); } if (UseSSL()) { Console.WriteLine("Using SSL"); app.UseHttpsRedirection(); } } // Add request logging to be able to identify attacks app.Use(async(ctx, next) => { if (ctx?.Connection?.RemoteIpAddress != null) { using (LogContext.PushProperty("IPAddress", ctx.Connection.RemoteIpAddress)) { await next(); } } }); app.UseSerilogRequestLogging(); // Hacker prevention app.UseCsp(csp => { if (RuntimeEnvironment.IsDevelopment() || RuntimeEnvironment.EnvironmentName.Equals("Local", StringComparison.InvariantCultureIgnoreCase)) { csp.AllowScripts .FromSelf() .From("http://localhost:4200") .From("https://localhost:6220") .From("http://localhost:6221") .From("https://www.googletagmanager.com") .AllowUnsafeInline() .AllowUnsafeEval(); csp.AllowStyles .FromSelf() .From("http://localhost:4200") .From("https://localhost:6220") .From("http://localhost:6221") .From("https://fonts.googleapis.com") .AllowUnsafeInline(); csp.AllowImages .FromSelf() .From("data:") .From("http://localhost:4200") .From("https://localhost:6220") .From("http://localhost:6221"); csp.AllowFonts.FromAnywhere(); } else { csp.AllowScripts .FromSelf() .From("https://www.googletagmanager.com") .AllowUnsafeInline() .AllowUnsafeEval(); csp.AllowStyles .FromSelf() .From("https://fonts.googleapis.com") .AllowUnsafeInline(); csp.AllowImages .FromSelf() .From("data:"); csp.AllowFonts .FromAnywhere(); } }) .UseXFrameOptions(new XFrameOptionsOptions(XFrameOptionsOptions.XFrameOptionsValues.Deny)) .UseReferrerPolicy(new ReferrerPolicyOptions(ReferrerPolicyOptions.ReferrerPolicyValue.NoReferrer)) .UseXXssProtection(new XXssProtectionOptions(true, true)) .UseXContentTypeOptions(new XContentTypeOptionsOptions(false)); app.UseResponseCompression(); app.UseStaticFiles(); if (!RuntimeEnvironment.IsDevelopment() && !RuntimeEnvironment.EnvironmentName.Equals("Local", StringComparison.InvariantCultureIgnoreCase)) { app.UseSpaStaticFiles(); } else { app.UseCors(c => c.WithOrigins("http://localhost:4200", "https://localhost:6220", "http://localhost:6221")); } // Consider making this publicly available if (RuntimeEnvironment.IsDevelopment() || RuntimeEnvironment.EnvironmentName.Equals("Local", StringComparison.InvariantCultureIgnoreCase)) { app.UseOpenApi(); // Access Swagger UI using https://localhost:6220/swagger/v1/swagger.json app.UseSwaggerUi3(s => { s.DocumentTitle = "CodeSwifterStarter API"; }); } if (RuntimeEnvironment.IsDevelopment()) { Console.WriteLine("Environment: " + RuntimeEnvironment.EnvironmentName); } app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(config => { config.MapControllerRoute( "api", "api/[controller]/{action}/{id?}"); config.MapControllerRoute( "auth", "auth/[controller]/{action}/{id?}"); }); if (!RuntimeEnvironment.IsDevelopment() && !RuntimeEnvironment.EnvironmentName.Equals("Local", StringComparison.InvariantCultureIgnoreCase)) { app.UseRootRewrite(); app.UseSpa(config => { }); } }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseXfo(options => options.SameOrigin()); app.UseCsp(config => { config.DefaultSources(cfg => cfg.Self()) .ScriptSources(cfg => cfg.Self().UnsafeEval()) .StyleSources(cfg => cfg.Self().UnsafeInline()) .FontSources(cfg => cfg.Self()) .ImageSources(cfg => cfg.Self().CustomSources("data:")) .FrameSources(cfg => cfg.Self().CustomSources("https://bif4-web-identity.azurewebsites.net")) .MediaSources(cfg => cfg.None()) .FrameAncestors(cfg => cfg.None()); if (env.IsDevelopment()) { // webpack needs websocket but ws:// urls aren't covered under "self" policy config.ConnectSources(cfg => cfg.CustomSources("*")); } else { config.ConnectSources(cfg => cfg.Self().CustomSources("https://bif4-web-identity.azurewebsites.net")); } }); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } 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. HstsBuilderExtensions.UseHsts(app); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseSpaStaticFiles(); app.UseAuthentication(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller}/{action=Index}/{id?}"); }); app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); }); 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.UseAngularCliServer(npmScript: "start"); } }); }