private static void InitializeDatabase(IWebHost host)
        {
            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;
                var logger   = services.GetRequiredService <ILogger <Program> >();

                try
                {
                    logger.LogInformation("Initializing the application database...");

                    var poTrackerDbContext = services.GetRequiredService <PoTrackerDbContext>();
                    PoTrackerDbInitializer.Initialize(poTrackerDbContext);

                    logger.LogInformation("Initializing the identity database...");
                    var context     = services.GetRequiredService <IdentityDbContext>();
                    var userManager = services.GetRequiredService <UserManager <ApplicationUser> >();
                    IdentityDbInitializer.Initialize(context, userManager);
                }
                catch (Exception ex)
                {
                    logger.LogError(ex, "An error occurred initializing the database");
                    throw;
                }
            }
        }
コード例 #2
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env,
                              UserManager <ApplicationUser> userManager,
                              RoleManager <ApplicationRole> roleManager)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            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();
            app.UseCookiePolicy();
            app.UseForwardedHeaders(new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
            });
            app.UseAuthentication();
            app.UseSession();
            IdentityDbInitializer.SeedData(userManager, roleManager);

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Product}/{action=Index}/{id?}");
            });
        }
コード例 #3
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app,
                              IHostingEnvironment env,
                              UserManager <ApplicationUsers> userManager,
                              RoleManager <ApplicationRoles> roleManager)
        {
            app.UseStaticFiles();
            app.UseAuthentication();
            app.UseSession();
            //First Time User Seed
            IdentityDbInitializer.SeedData(userManager, roleManager);



            if (env.IsDevelopment())
            {
                app.UseMiddleware <StackifyMiddleware.RequestTracerMiddleware>();
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
コード例 #4
0
        // 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)
        {
            if (env.IsDevelopment())
            {
                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();

            IdentityDbInitializer.SeedUsers(userManager);

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
            });
        }
コード例 #5
0
ファイル: Program.cs プロジェクト: maikeulb/RolleiShop
        public static void Main(string[] args)
        {
            var host = BuildWebHost(args);

            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;
                try
                {
                    var applicationDbContext           = services.GetRequiredService <ApplicationDbContext> ();
                    var applicationDbInitializerLogger = services.GetRequiredService <ILogger <ApplicationDbInitializer> > ();
                    ApplicationDbInitializer.Initialize(applicationDbContext, applicationDbInitializerLogger).Wait();

                    var userManager   = services.GetRequiredService <UserManager <ApplicationUser> > ();
                    var roleManager   = services.GetRequiredService <RoleManager <IdentityRole> > ();
                    var configuration = services.GetRequiredService <IConfiguration> ();
                    var identityDbInitializerLogger = services.GetRequiredService <ILogger <IdentityDbInitializer> > ();
                    IdentityDbInitializer.Initialize(userManager, roleManager, configuration).Wait();
                }
                catch (Exception ex)
                {
                    var logger = services.GetRequiredService <ILogger <Program> > ();
                    logger.LogError(ex, "An error occurred while seeding the database.");
                }
            }

            host.Run();
        }
コード例 #6
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseHttpsRedirection();
            app.UseCors("CorsPolicy");

            app.UseSignalR(routes =>
            {
                routes.MapHub <ChatHub>("/chathub");
            });

            app.UseDeveloperExceptionPage();
            app.UseAuthentication();
            app.UseStaticFiles();
            app.UseSpaStaticFiles();
            app.UseMvc();
            app.UseSpa(spa =>
            {
                spa.Options.SourcePath = "App";
                if (env.IsDevelopment())
                {
                    spa.UseAngularCliServer(npmScript: "start");
                }
                //else
                //{
                //    spa.UseAngularCliServer(npmScript: "build");
                //}
            });

            IdentityDbInitializer.SeedData(app).Wait();
        }
コード例 #7
0
        public static void Main(string[] args)
        {
            var host = BuildWebHost(args);

            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;
                try
                {
                    //var context = services.GetRequiredService<SchoolContext>();
                    //Creating a more complex data model - comment out line below
                    //This DbInitializer is for the School Data
                    //DbInitializer.Initialize(context);

                    //mwilliams:  Identity Framework - initial seed
                    //Note:  using the Secrets Manager tool for initial pwd
                    //       will need a reference to the Microsoft.Extensions.Configuration
                    //This DbInitializer is for user and roles within the Identity Framework
                    var config = host.Services.GetRequiredService <IConfiguration>();

                    var testUserPw = config["SeedUserPW"];//this is the password

                    //Call our Initializer
                    IdentityDbInitializer.Initialize(services, testUserPw).Wait();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            host.Run();
            //old code
            //BuildWebHost(args).Run();
        }
コード例 #8
0
        public static async Task Main(string[] args)
        {
            var host = CreateHostBuilder(args).Build();

            using (var scope = host.Services.CreateScope())
            {
                var services     = scope.ServiceProvider;
                var userManager  = services.GetRequiredService <UserManager <User> >();
                var rolesManager = services.GetRequiredService <RoleManager <IdentityRole> >();
                await IdentityDbInitializer.InitializeAsync(userManager, rolesManager);
            }

            await host.RunAsync();
        }
コード例 #9
0
        public static void Main(string[] args)
        {
            try
            {
                var host = Host.CreateDefaultBuilder(args)
                           .UseContentRoot(Directory.GetCurrentDirectory())
                           .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder
                    .UseKestrel()
                    .UseIIS()
                    .UseStartup <Startup>();
                }).Build();

                //host.Run();
                //var host = CreateWebHostBuilder(args).Build();

                using (var scope = host.Services.CreateScope())
                {
                    var services = scope.ServiceProvider;
                    try
                    {
                        var context = services.GetRequiredService <ApplicationDbContext>();

                        var roleManager = services.GetRequiredService <RoleManager <IdentityRole> >();
                        var userManager = services.GetRequiredService <UserManager <ApplicationUser> >();

                        IdentityDbInitializer.Initialize(context, userManager, roleManager);
                        DbInitializer.Initialize(context);
                    }
                    catch (Exception ex)
                    {
                        var logger = services.GetRequiredService <ILogger <Program> >();
                        logger.LogError(ex, "An error occurred while seeding the database.");
                    }
                }

                host.Run();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            //CreateWebHostBuilder(args).Build().Run();
        }
コード例 #10
0
        public static void Main(string[] args)
        {
            var host = BuildWebHost(args);

            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;
                try
                {
                    IdentityDbInitializer.Initialize(services).Wait();
                    var context = services.GetRequiredService <AnimalContext>();
                    //DbInitializer.Initialize(context);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            //BuildWebHost(args).Run();
            host.Run();
        }
コード例 #11
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app,
                              IWebHostEnvironment env,
                              UserManager <ApplicationUsers> userManager,
                              RoleManager <ApplicationRoles> roleManager)
        {
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthentication();

            app.UseAuthorization();

            app.UseStaticFiles();

            IdentityDbInitializer.SeedData(userManager, roleManager);


            if (env.IsDevelopment())
            {
                app.UseMiddleware <StackifyMiddleware.RequestTracerMiddleware>();
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
コード例 #12
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();
        }
コード例 #13
0
        // 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, A2SPAContext context, IdentityContext identityContext)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            // Add a middleware used to validate access
            // tokens and protect the API endpoints.
            app.UseOAuthValidation();

            // Alternatively, you can also use the introspection middleware.
            // Using it is recommended if your resource server is in a
            // different application/separated from the authorization server.
            //
            // app.UseOAuthIntrospection(options =>
            // {
            //     options.AutomaticAuthenticate = true;
            //     options.AutomaticChallenge = true;
            //     options.Authority = "http://localhost:58795/";
            //     options.Audiences.Add("resource_server");
            //     options.ClientId = "resource_server";
            //     options.ClientSecret = "875sqd4s5d748z78z7ds1ff8zz8814ff88ed8ea4z4zzd";
            // });

            app.UseOpenIddict();

            app.UseDefaultFiles();
            app.UseStaticFiles();
            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "node_modules")),
                RequestPath  = "/node_modules"
            });

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

                // in case multiple SPAs required.
                routes.MapSpaFallbackRoute("spa-fallback", new { controller = "home", action = "index" });
            });

            if (env.IsDevelopment())
            {
                app.UseSwaggerUi(typeof(Startup).GetTypeInfo().Assembly, new SwaggerUiOwinSettings()
                {
                    OperationProcessors =
                    {
                        new OperationSecurityScopeProcessor("apikey")
                    },
                    DocumentProcessors =
                    {
                        new SecurityDefinitionAppender("apikey", new SwaggerSecurityScheme
                        {
                            Type = SwaggerSecuritySchemeType.ApiKey,
                            Name = "Authorization",
                            In   = SwaggerSecurityApiKeyLocation.Header
                        })
                    },
                    DefaultPropertyNameHandling = PropertyNameHandling.CamelCase
                });

                IdentityDbInitializer.Initialize(identityContext);
                DbInitializer.Initialize(context);
            }
        }