コード例 #1
0
        /// <summary>
        /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        /// </summary>
        /// <param name="app">The application.</param>
        /// <param name="env">The env.</param>
        /// <param name="loggerFactory">The logger factory.</param>
        /// <param name="portfolioSeeder">The portfolio seeder.</param>
        /// <param name="identitySeeder">The identity seeder.</param>
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, PortfolioDbInitializer portfolioSeeder, IdentityDbInitializer identitySeeder)
        {
            //Add Logging
            loggerFactory.AddConsole(_config.GetSection("Logging"));
            if (env.IsDevelopment())
            {
                loggerFactory.AddDebug();
            }

            // Add MVC to the request pipeline.
            app.UseCors(builder =>
                        builder.AllowAnyOrigin()
                        .AllowAnyHeader()
                        .AllowAnyMethod());

            //Enable Identity
            app.UseIdentity();

            //Make use of JWT Web tokens
            app.UseJwtBearerAuthentication(new JwtBearerOptions()
            {
                AutomaticAuthenticate     = true,
                AutomaticChallenge        = true,
                TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidIssuer              = _config["Tokens:Issuer"],
                    ValidAudience            = _config["Tokens:Audience"],
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"])),
                    ValidateLifetime         = true
                }
            });

            //Add Security Headers
            if (env.IsProduction())
            {
                app.UseSecurityHeadersMiddleware(new SecurityHeadersBuilder()
                                                 .AddDefaultSecurePolicy()
                                                 .AddCustomHeader("Referrer-Policy", "origin")
                                                 .AddCustomHeader("Content-Security-Policy", "default-src https://somedomain.org:*; script-src https://somedomain.org:* 'unsafe-inline'; style-src https://somedomain.org:* 'unsafe-inline'")
                                                 .AddCustomHeader("Public-Key-Pins", "pin-sha256=\"\"; max-age=2592000; includeSubdomains;") //Generate yours here: https://report-uri.io/home/pkp_analyse/
                                                 .AddCustomHeader("X-Additional-Security", "More Security. Nothing to see here.")
                                                 );
            }

            //Add exception handling
            app.UseExceptionHandler(
                builder =>
            {
                builder.Run(
                    async context =>
                {
                    context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                    context.Response.Headers.Add("Access-Control-Allow-Origin", "*");

                    var error = context.Features.Get <IExceptionHandlerFeature>();
                    if (error != null)
                    {
                        context.Response.AddApplicationError(error.Error.Message);
                        await context.Response.WriteAsync(error.Error.Message).ConfigureAwait(false);
                    }
                });
            });

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");

                routes.MapRoute(
                    name: "ChildApi",
                    template: "api/{parentController}/{parentId}/{controller}/{id}");

                // Uncomment the following line to add a route for porting Web API 2 controllers.
                //routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
            });

            //Add the Swagger UI middleware
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "Portfolio API V1");
            });

            //Initialize the database
            portfolioSeeder.Seed();
            identitySeeder.Seed();
        }
コード例 #2
0
ファイル: Startup.cs プロジェクト: pietermyb/portfolio
        /// <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>
        /// <param name="loggerFactory"></param>
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            //Add Logging
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
#if DEBUG
            loggerFactory.AddDebug();
#endif

            // Add MVC to the request pipeline.
            app.UseCors(builder =>
                        builder.AllowAnyOrigin()
                        .AllowAnyHeader()
                        .AllowAnyMethod());

            //Add Security Headers
            app.UseSecurityHeadersMiddleware(new SecurityHeadersBuilder()
                                             .AddDefaultSecurePolicy()
                                             .AddCustomHeader("Referrer-Policy", "same-origin")
                                             .AddCustomHeader("X-Pamyb-Security", "PAMYB.org Security. Nothing to see here.")
                                             );

            //Add exception handling
            app.UseExceptionHandler(
                builder =>
            {
                builder.Run(
                    async context =>
                {
                    context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                    context.Response.Headers.Add("Access-Control-Allow-Origin", "*");

                    var error = context.Features.Get <IExceptionHandlerFeature>();
                    if (error != null)
                    {
                        context.Response.AddApplicationError(error.Error.Message);
                        await context.Response.WriteAsync(error.Error.Message).ConfigureAwait(false);
                    }
                });
            });

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");

                routes.MapRoute(
                    name: "ChildApi",
                    template: "api/{parentController}/{parentId}/{controller}/{id}");

                // Uncomment the following line to add a route for porting Web API 2 controllers.
                //routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
            });

            //Add the Swagger UI middleware
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "Portfolio API V1");
            });

            //Initialize the database
            PortfolioDbInitializer.Initialize(app.ApplicationServices);
        }