コード例 #1
0
        public void Configuration(IAppBuilder app)
        {
            // set up Entity Framework Migrations
            Database.SetInitializer(new MigrateDatabaseToLatestVersion <AppContext, DataAccess.Migrations.Configuration>());

            // use cookie authentication
            app.UseCookieAuthentication(new CookieAuthenticationOptions()
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/"),
                Provider           = new CookieAuthenticationProvider()
                {
                    OnApplyRedirect = context =>
                    {
                        DotvvmAuthenticationHelper.ApplyRedirectResponse(context.OwinContext, context.RedirectUri);
                    }
                }
            });

            // use DotVVM
            var applicationPhysicalPath = HostingEnvironment.ApplicationPhysicalPath;
            var dotvvmConfiguration     = app.UseDotVVM <DotvvmStartup>(applicationPhysicalPath);

            ConfigureDotvvmServices(dotvvmConfiguration);


            // use static files
            app.UseStaticFiles(new StaticFileOptions()
            {
                FileSystem = new PhysicalFileSystem(applicationPhysicalPath)
            });
        }
コード例 #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, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole();

            app.UseMiniProfiler(new MiniProfilerOptions
            {
                RouteBasePath = "~/profiler",
                Storage       = new MemoryCacheStorage(new MemoryCache(new MemoryCacheOptions()), TimeSpan.FromMinutes(60))
            });

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                LoginPath            = new PathString("/"),
                AuthenticationScheme = "Cookie",
                Events = new CookieAuthenticationEvents
                {
                    OnRedirectToReturnUrl    = c => DotvvmAuthenticationHelper.ApplyRedirectResponse(c.HttpContext, c.RedirectUri),
                    OnRedirectToAccessDenied = c => DotvvmAuthenticationHelper.ApplyStatusCodeResponse(c.HttpContext, 403),
                    OnRedirectToLogin        = c => DotvvmAuthenticationHelper.ApplyRedirectResponse(c.HttpContext, c.RedirectUri),
                    OnRedirectToLogout       = c => DotvvmAuthenticationHelper.ApplyRedirectResponse(c.HttpContext, c.RedirectUri)
                },
                AutomaticAuthenticate = true,
                AutomaticChallenge    = true
            });

            // use DotVVM
            var dotvvmConfiguration = app.UseDotVVM <DotvvmStartup>(env.ContentRootPath);

            // use static files
            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new Microsoft.Extensions.FileProviders.PhysicalFileProvider(env.WebRootPath)
            });
        }
コード例 #3
0
        public void ConfigureServices(IServiceCollection services)
        {
            // Configure DB context
            services.AddDbContext <AskDbContext>(options =>
            {
                options.UseSqlServer(_config.GetConnectionString(ConnectionStringName));
                // options.UseSqlite(_config.GetConnectionString(ConnectionStringName));
            });

            //var s = new System.Data.SqlClient.SqlConnection();


            services.AddSingleton <Func <IDbConnection> >(x => () => new SqlConnection(_config.GetConnectionString(ConnectionStringName)));


            services.AddSingleton <IDbConnectionFactory, DbConnectionFactory>();

            services.AddMapping(typeof(Data.Transfer.Objects.CategoryListItemDto).Assembly);

            services.AddCommanding(typeof(Data.Commands.InsertQuestionCommand).Assembly, typeof(AskCommandHandler <>).Assembly);

            services.AddQuerying(
                typeof(Data.Queries.CategoriesListItemsQuery).Assembly,
                typeof(Olbrasoft.AskMe.Data.Dapper.QueryHandlers.PagedAnsweredQuestionsQueryHandler).Assembly
                );

            services.AddBusiness();

            // Configure identity and authentication
            services.AddIdentity <ApplicationUser, ApplicationRole>(options => {
                options.Password.RequiredLength         = 12;
                options.Password.RequiredUniqueChars    = 4;
                options.Password.RequireDigit           = false;
                options.Password.RequireLowercase       = false;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = false;
            })
            .AddEntityFrameworkStores <AskDbContext>()
            .AddDefaultTokenProviders();
            services.ConfigureApplicationCookie(options => {
                options.LoginPath                = "/Account/Login";
                options.LogoutPath               = "/Account/Logout";
                options.SlidingExpiration        = true;
                options.ExpireTimeSpan           = TimeSpan.FromDays(30);
                options.Events.OnRedirectToLogin = context => DotvvmAuthenticationHelper.ApplyRedirectResponse(context.HttpContext, context.RedirectUri);
            });

            // Load configuration
            services.Configure <AppConfiguration>(this._config);

            services.AddDotVVM <DotvvmStartup>();

            services.AddScoped <RssPresenter>();

            // AutoMapper config
            MapperConfig.Configure();
        }
コード例 #4
0
 private static void ConfigureCookieAuthentication(IAppBuilder app)
 {
     app.UseCookieAuthentication(new CookieAuthenticationOptions()
     {
         LoginPath          = new PathString("/"),
         AuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
         Provider           = new CookieAuthenticationProvider()
         {
             OnApplyRedirect = context => { DotvvmAuthenticationHelper.ApplyRedirectResponse(context.OwinContext, context.RedirectUri); }
         }
     });
 }
コード例 #5
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDataProtection();
            services.AddAuthorization();
            services.AddWebEncoders();
            services.AddDotVVM();

            services.AddAuthentication(sharedOptions =>
            {
                sharedOptions.DefaultScheme          = CookieAuthenticationDefaults.AuthenticationScheme;
                sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
            })
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
            {
                options.ClientId             = Configuration["AzureAD:ClientId"];
                options.Authority            = string.Format(Configuration["AzureAd:AadInstance"], Configuration["AzureAd:Tenant"]);
                options.SignedOutRedirectUri = Configuration["AzureAd:PostLogoutRedirectUri"];

                // Uncomment the following section if you need "code" response type
                // options.ResponseType = "code";
                // options.ClientSecret = "Configuration["AzureAd:ClientSecret"];

                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuer = (Configuration["AzureAd:Tenant"] != "common")
                };

                options.Events = new OpenIdConnectEvents
                {
                    OnRemoteFailure = context =>
                    {
                        context.HandleResponse();
                        context.Response.Redirect("/error");
                        return(Task.CompletedTask);
                    },
                    OnRedirectToIdentityProvider = context =>
                    {
                        var message = context.ProtocolMessage;

                        if (!string.IsNullOrEmpty(message.State))
                        {
                            context.Properties.Items[OpenIdConnectDefaults.UserstatePropertiesKey] = message.State;
                        }

                        context.Properties.Items.Add(OpenIdConnectDefaults.RedirectUriForCodePropertiesKey, message.RedirectUri);
                        message.State = context.Options.StateDataFormat.Protect(context.Properties);
                        DotvvmAuthenticationHelper.ApplyRedirectResponse(context.HttpContext, message.BuildRedirectUrl());
                        return(Task.CompletedTask);
                    }
                };
            });
        }
コード例 #6
0
ファイル: Startup.cs プロジェクト: llenroc/dotvvm
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            var supportedCultures = new[] {
                new CultureInfo("en-US"),
                new CultureInfo("cs-CZ")
            };

            app.UseCookieAuthentication(new CookieAuthenticationOptions {
                LoginPath            = new PathString("/ComplexSamples/Auth/Login"),
                AuthenticationScheme = "Scheme1",
                Events = new CookieAuthenticationEvents {
                    OnRedirectToReturnUrl    = c => DotvvmAuthenticationHelper.ApplyRedirectResponse(c.HttpContext, c.RedirectUri),
                    OnRedirectToAccessDenied = c => DotvvmAuthenticationHelper.ApplyStatusCodeResponse(c.HttpContext, 403),
                    OnRedirectToLogin        = c => DotvvmAuthenticationHelper.ApplyRedirectResponse(c.HttpContext, c.RedirectUri),
                    OnRedirectToLogout       = c => DotvvmAuthenticationHelper.ApplyRedirectResponse(c.HttpContext, c.RedirectUri)
                }
            });

            app.UseCookieAuthentication(new CookieAuthenticationOptions {
                LoginPath            = new PathString("/ComplexSamples/SPARedirect/login"),
                AuthenticationScheme = "Scheme2",
                Events = new CookieAuthenticationEvents {
                    OnRedirectToReturnUrl    = c => DotvvmAuthenticationHelper.ApplyRedirectResponse(c.HttpContext, c.RedirectUri),
                    OnRedirectToAccessDenied = c => DotvvmAuthenticationHelper.ApplyStatusCodeResponse(c.HttpContext, 403),
                    OnRedirectToLogin        = c => DotvvmAuthenticationHelper.ApplyRedirectResponse(c.HttpContext, c.RedirectUri),
                    OnRedirectToLogout       = c => DotvvmAuthenticationHelper.ApplyRedirectResponse(c.HttpContext, c.RedirectUri)
                }
            });

            app.UseCookieAuthentication(new CookieAuthenticationOptions {
                AuthenticationScheme = "Scheme3"
            });

            app.UseRequestLocalization(new RequestLocalizationOptions {
                DefaultRequestCulture   = new RequestCulture("en-US"),
                SupportedCultures       = supportedCultures,
                SupportedUICultures     = supportedCultures,
                RequestCultureProviders = new List <IRequestCultureProvider> {
                    new QueryStringRequestCultureProvider {
                        QueryStringKey = "lang"
                    }
                }
            });

            var config = app.UseDotVVM <DotvvmStartup>(GetApplicationPath(env));

            config.RouteTable.Add("AuthorizedPresenter", "ComplexSamples/Auth/AuthorizedPresenter", null, null, () => new AuthorizedPresenter());

            app.UseStaticFiles();
        }
コード例 #7
0
        public void Configuration(IAppBuilder app)
        {
            app.Use <SwitchMiddleware>(
                new List <SwitchMiddlewareCase> {
                new SwitchMiddlewareCase(
                    c => c.Request.Uri.PathAndQuery.StartsWith("/ComplexSamples/Auth"), next =>
                    new CookieAuthenticationMiddleware(next, app, new CookieAuthenticationOptions {
                    LoginPath          = new PathString("/ComplexSamples/Auth/Login"),
                    AuthenticationType = "ApplicationCookie",
                    Provider           = new CookieAuthenticationProvider {
                        OnApplyRedirect = c => DotvvmAuthenticationHelper.ApplyRedirectResponse(c.OwinContext, c.RedirectUri)
                    }
                })
                    ),
                new SwitchMiddlewareCase(
                    c => c.Request.Uri.PathAndQuery.StartsWith("/ComplexSamples/SPARedirect"), next =>
                    new CookieAuthenticationMiddleware(next, app, new CookieAuthenticationOptions {
                    LoginPath          = new PathString("/ComplexSamples/SPARedirect/login"),
                    AuthenticationType = "ApplicationCookie",
                    Provider           = new CookieAuthenticationProvider {
                        OnApplyRedirect = c => DotvvmAuthenticationHelper.ApplyRedirectResponse(c.OwinContext, c.RedirectUri)
                    }
                })
                    ),
                new SwitchMiddlewareCase(
                    c => c.Request.Uri.PathAndQuery.StartsWith("/ControlSamples/AuthenticatedView") ||
                    c.Request.Uri.PathAndQuery.StartsWith("/ControlSamples/RoleView") ||
                    c.Request.Uri.PathAndQuery.StartsWith("/ControlSamples/ClaimView"), next =>
                    new CookieAuthenticationMiddleware(next, app, new CookieAuthenticationOptions {
                    AuthenticationType = "ApplicationCookie"
                })
                    )
            }
                );

            var config = app.UseDotVVM <DotvvmStartup>(GetApplicationPath(), modifyConfiguration: c => {
                c.RouteTable.Add("AuthorizedPresenter", "ComplexSamples/Auth/AuthorizedPresenter", provider => new AuthorizedPresenter());

                if (c.ExperimentalFeatures.ExplicitAssemblyLoading.Enabled)
                {
                    c.Markup.AddAssembly(typeof(Startup).Assembly.FullName);
                }
            });

#if AssertConfiguration
            // this compilation symbol is set by CI server
            config.AssertConfigurationIsValid();
#endif
            app.UseStaticFiles();
        }
コード例 #8
0
 public void ConfigureAuth(IAppBuilder app)
 {
     app.UseCookieAuthentication(new CookieAuthenticationOptions()
     {
         AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
         LoginPath          = new PathString("/Authentication/SignIn"),
         Provider           = new CookieAuthenticationProvider()
         {
             OnApplyRedirect = context =>
             {
                 DotvvmAuthenticationHelper.ApplyRedirectResponse(context.OwinContext, context.RedirectUri);
             }
         }
     });
 }
コード例 #9
0
ファイル: Startup.cs プロジェクト: DavidSilwal/dotvvm
        public void Configuration(IAppBuilder app)
        {
            app.Use <SwitchMiddleware>(
                new List <SwitchMiddlewareCase> {
                new SwitchMiddlewareCase(
                    c => c.Request.Uri.PathAndQuery.StartsWith("/ComplexSamples/Auth"), next =>
                    new CookieAuthenticationMiddleware(next, app, new CookieAuthenticationOptions {
                    LoginPath          = new PathString("/ComplexSamples/Auth/Login"),
                    AuthenticationType = "ApplicationCookie",
                    Provider           = new CookieAuthenticationProvider {
                        OnApplyRedirect = c => DotvvmAuthenticationHelper.ApplyRedirectResponse(c.OwinContext, c.RedirectUri)
                    }
                })
                    ),
                new SwitchMiddlewareCase(
                    c => c.Request.Uri.PathAndQuery.StartsWith("/ComplexSamples/SPARedirect"), next =>
                    new CookieAuthenticationMiddleware(next, app, new CookieAuthenticationOptions {
                    LoginPath          = new PathString("/ComplexSamples/SPARedirect/login"),
                    AuthenticationType = "ApplicationCookie",
                    Provider           = new CookieAuthenticationProvider {
                        OnApplyRedirect = c => DotvvmAuthenticationHelper.ApplyRedirectResponse(c.OwinContext, c.RedirectUri)
                    }
                })
                    ),
                new SwitchMiddlewareCase(
                    c => c.Request.Uri.PathAndQuery.StartsWith("/ControlSamples/AuthenticatedView") ||
                    c.Request.Uri.PathAndQuery.StartsWith("/ControlSamples/RoleView") ||
                    c.Request.Uri.PathAndQuery.StartsWith("/ControlSamples/ClaimView"), next =>
                    new CookieAuthenticationMiddleware(next, app, new CookieAuthenticationOptions {
                    AuthenticationType = "ApplicationCookie"
                })
                    )
            }
                );
            var config = app.UseDotVVM <DotvvmStartup>(GetApplicationPath(), options: b =>
            {
                CommonConfiguration.ConfigureServices(b.Services);
                b.AddDefaultTempStorages("Temp");
                b.Services.AddScoped <ViewModelScopedDependency>();
                b.Services.AddSingleton <IGreetingComputationService, HelloGreetingComputationService>();
            });

            config.RouteTable.Add("AuthorizedPresenter", "ComplexSamples/Auth/AuthorizedPresenter", null, null, () => new AuthorizedPresenter());

            app.UseStaticFiles();
        }
コード例 #10
0
ファイル: Startup.cs プロジェクト: vaclavnovotny/dotvvm
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication("Scheme1")
            .AddCookie("Scheme1", o => {
                o.LoginPath = new PathString("/ComplexSamples/Auth/Login");
                o.Events    = new CookieAuthenticationEvents {
                    OnRedirectToReturnUrl    = c => DotvvmAuthenticationHelper.ApplyRedirectResponse(c.HttpContext, c.RedirectUri),
                    OnRedirectToAccessDenied = c => DotvvmAuthenticationHelper.ApplyStatusCodeResponse(c.HttpContext, 403),
                    OnRedirectToLogin        = c => DotvvmAuthenticationHelper.ApplyRedirectResponse(c.HttpContext, c.RedirectUri),
                    OnRedirectToLogout       = c => DotvvmAuthenticationHelper.ApplyRedirectResponse(c.HttpContext, c.RedirectUri)
                };
            });

            services.AddAuthentication("Scheme2")
            .AddCookie("Scheme2", o => {
                o.LoginPath = new PathString("/ComplexSamples/SPARedirect/login");
                o.Events    = new CookieAuthenticationEvents {
                    OnRedirectToReturnUrl    = c => DotvvmAuthenticationHelper.ApplyRedirectResponse(c.HttpContext, c.RedirectUri),
                    OnRedirectToAccessDenied = c => DotvvmAuthenticationHelper.ApplyStatusCodeResponse(c.HttpContext, 403),
                    OnRedirectToLogin        = c => DotvvmAuthenticationHelper.ApplyRedirectResponse(c.HttpContext, c.RedirectUri),
                    OnRedirectToLogout       = c => DotvvmAuthenticationHelper.ApplyRedirectResponse(c.HttpContext, c.RedirectUri)
                };
            });

            services.AddAuthentication("Scheme3")
            .AddCookie("Scheme3");


            services.AddLocalization(o => o.ResourcesPath = "Resources");

            services.AddDotVVM(options =>
            {
                CommonConfiguration.ConfigureServices(options.Services);
                options.AddDefaultTempStorages("Temp");
            });

            services.Configure <BindingCompilationOptions>(o => {
                o.TransformerClasses.Add(new BindingTestResolvers());
            });

            services.AddSingleton <IGreetingComputationService, HelloGreetingComputationService>();

            services.AddScoped <ViewModelScopedDependency>();
        }
コード例 #11
0
ファイル: Startup.cs プロジェクト: fabbbiob/dotvvm
        public void Configuration(IAppBuilder app)
        {
            app.Use <SwitchMiddleware>(
                new List <SwitchMiddlewareCase> {
                new SwitchMiddlewareCase(
                    c => c.Request.Uri.PathAndQuery.StartsWith("/ComplexSamples/Auth"), next =>
                    new CookieAuthenticationMiddleware(next, app, new CookieAuthenticationOptions {
                    LoginPath          = new PathString("/ComplexSamples/Auth/Login"),
                    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                    Provider           = new CookieAuthenticationProvider {
                        OnApplyRedirect = c => DotvvmAuthenticationHelper.ApplyRedirectResponse(c.OwinContext, c.RedirectUri)
                    }
                })
                    ),
                new SwitchMiddlewareCase(
                    c => c.Request.Uri.PathAndQuery.StartsWith("/ComplexSamples/SPARedirect"), next =>
                    new CookieAuthenticationMiddleware(next, app, new CookieAuthenticationOptions {
                    LoginPath          = new PathString("/ComplexSamples/SPARedirect/login"),
                    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                    Provider           = new CookieAuthenticationProvider {
                        OnApplyRedirect = c => DotvvmAuthenticationHelper.ApplyRedirectResponse(c.OwinContext, c.RedirectUri)
                    }
                })
                    ),
                new SwitchMiddlewareCase(
                    c => c.Request.Uri.PathAndQuery.StartsWith("/ControlSamples/AuthenticatedView") ||
                    c.Request.Uri.PathAndQuery.StartsWith("/ControlSamples/RoleView") ||
                    c.Request.Uri.PathAndQuery.StartsWith("/ControlSamples/ClaimView"), next =>
                    new CookieAuthenticationMiddleware(next, app, new CookieAuthenticationOptions {
                    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie
                })
                    )
            }
                );

            var config = app.UseDotVVM <DotvvmStartup>(GetApplicationPath(), builder: b => { b.ConfigureTempStorages("Temp"); });

            config.RouteTable.Add("AuthorizedPresenter", "ComplexSamples/Auth/AuthorizedPresenter", null, null, () => new AuthorizedPresenter());

            app.UseStaticFiles();
        }
コード例 #12
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CustomJwtOptions>(Configuration.GetSection("CustomJwt"));

            services.AddMvc();
            services.AddDotVVM <DotvvmStartup>();

            services.AddAuthentication(sharedOptions =>
            {
                sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            })
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
            {
                options.Events = new CookieAuthenticationEvents
                {
                    OnRedirectToReturnUrl    = c => DotvvmAuthenticationHelper.ApplyRedirectResponse(c.HttpContext, c.RedirectUri),
                    OnRedirectToAccessDenied = c => DotvvmAuthenticationHelper.ApplyStatusCodeResponse(c.HttpContext, 403),
                    OnRedirectToLogin        = c => DotvvmAuthenticationHelper.ApplyRedirectResponse(c.HttpContext, c.RedirectUri),
                    OnRedirectToLogout       = c => DotvvmAuthenticationHelper.ApplyRedirectResponse(c.HttpContext, c.RedirectUri)
                };
                options.LoginPath = "/Login";
            })
            .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
            {
                var jwt = Configuration.GetSection("CustomJwt").Get <CustomJwtOptions>();

                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer      = jwt.Issuer,
                    ValidAudience    = jwt.Audience,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwt.Key))
                };
            });

            services.AddHttpContextAccessor();
            services.AddTransient <MvcUtility>();
        }
コード例 #13
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddApplicationInsightsTelemetry(configuration);

            services.AddDataProtection();
            services.AddAuthorization();
            services.AddWebEncoders();

            services.AddDotVVM <DotvvmStartup>();

            services
            .AddAuthentication("Cookie")
            .AddCookie("Cookie", options =>
            {
                options.LoginPath = new PathString("/");
                options.Events    = new CookieAuthenticationEvents
                {
                    OnRedirectToReturnUrl    = c => DotvvmAuthenticationHelper.ApplyRedirectResponse(c.HttpContext, c.RedirectUri),
                    OnRedirectToAccessDenied = c => DotvvmAuthenticationHelper.ApplyStatusCodeResponse(c.HttpContext, 403),
                    OnRedirectToLogin        = c => DotvvmAuthenticationHelper.ApplyRedirectResponse(c.HttpContext, c.RedirectUri),
                    OnRedirectToLogout       = c => DotvvmAuthenticationHelper.ApplyRedirectResponse(c.HttpContext, c.RedirectUri)
                };
            });

            services.AddMemoryCache();

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            services.Configure <MiniProfilerOptions>(options =>
            {
                options.RouteBasePath = "/profiler";
                options.Storage       = new MemoryCacheStorage(new MemoryCache(new MemoryCacheOptions()), TimeSpan.FromMinutes(60));
            });

            return(WindsorRegistrationHelper.CreateServiceProvider(InitializeWindsor(), services));
        }
コード例 #14
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDataProtection();
            services.AddResponseCompression(opt => opt.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(new[] { "image/svg+xml" }));

            var adminPolicy = new AuthorizationPolicyBuilder(new[] { CookieAuthenticationDefaults.AuthenticationScheme })
                              .RequireAuthenticatedUser()
                              .RequireRole(new[] { nameof(Roles.Administrator) })
                              .Build();

            var userPolicy = new AuthorizationPolicyBuilder(new[] { CookieAuthenticationDefaults.AuthenticationScheme })
                             .RequireAuthenticatedUser()
                             .Build();

            services.AddAuthorization(options =>
            {
                options.AddPolicy(nameof(Roles.User), userPolicy);
                options.AddPolicy(nameof(Roles.Administrator), adminPolicy);
            });

            services.AddWebEncoders();

            services.Configure <AppSettings>(Configuration);

            services.AddDbContext <BootstrapDbContext>(opt =>
            {
                opt.UseInMemoryDatabase("BootstrapDb");
                opt.ConfigureWarnings(w => w.Ignore(InMemoryEventId.TransactionIgnoredWarning));
            });

            //services.AddDbContext<BootstrapDbContext>(opt => {
            //    var bootstrapDb = Configuration.GetValue<string>(nameof(AppSettings.BootstrapDb));
            //    opt.UseSqlServer(bootstrapDb, o => o.UseRowNumberForPaging());
            //    opt.ConfigureWarnings(w => w.Ignore(InMemoryEventId.TransactionIgnoredWarning));
            //});

            services.AddIdentity <User, Role>(config =>
            {
                config.Password.RequireDigit           = false;
                config.Password.RequiredLength         = 0;
                config.Password.RequiredUniqueChars    = 0;
                config.Password.RequireLowercase       = false;
                config.Password.RequireUppercase       = false;
                config.Password.RequireNonAlphanumeric = false;
            })
            .AddEntityFrameworkStores <BootstrapDbContext>()
            .AddDefaultTokenProviders();

            services
            .AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
            {
                options.LoginPath = new PathString("/login");
                options.Events    = new CookieAuthenticationEvents
                {
                    OnRedirectToReturnUrl    = async c => await DotvvmAuthenticationHelper.ApplyRedirectResponse(c.HttpContext, c.RedirectUri),
                    OnRedirectToAccessDenied = async c => await DotvvmAuthenticationHelper.ApplyStatusCodeResponse(c.HttpContext, 403),
                    OnRedirectToLogin        = async c => await DotvvmAuthenticationHelper.ApplyRedirectResponse(c.HttpContext, c.RedirectUri),
                    OnRedirectToLogout       = async c => await DotvvmAuthenticationHelper.ApplyRedirectResponse(c.HttpContext, c.RedirectUri),
                    OnValidatePrincipal      = async c => await ValidateAsync(c)
                };
            });

            services
            .ConfigureApplicationCookie(options => options.LoginPath = new PathString("/login"));

            services.AddScoped <ExampleRecordService>();
            services.AddScoped <SettingsService>();
            services.AddScoped <IDbInitializer, DbInitializer>();

            services.AddDotVVM();
        }
コード例 #15
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDataProtection();
            services.AddAuthorization();
            services.AddWebEncoders();

            services.AddDotVVM <DotvvmStartup>();

            // presenters
            services.AddScoped <IdenticonPresenter>();

            // helpers
            services.AddSingleton <FileStorageHelper>();
            services.Configure <LoginOptions>(Configuration.GetSection("loginOptions"));
            services.AddScoped <LoginHelper>();

            // services
            services.AddScoped <GroupService>();
            services.AddScoped <PaymentService>();
            services.AddScoped <SettlementService>();
            services.AddScoped <UserService>();
            services.AddScoped <DataSeedingService>();

            // database
            services.AddEntityFrameworkSqlite()
            .AddDbContext <AppDbContext>(options =>
            {
                options.UseSqlite(Configuration.GetSection("dbOptions").GetValue <string>("connectionString"));
            });

            var loginOptions = Configuration.GetSection("loginOptions").Get <LoginOptions>();

            // authentication
            var authBuilder = services.AddAuthentication(sharedOptions =>
            {
                sharedOptions.DefaultScheme          = CookieAuthenticationDefaults.AuthenticationScheme;
                sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
            })
                              .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme);

            if (loginOptions.AADEnabled)
            {
                authBuilder.AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
                {
                    options.ClientId                  = loginOptions.ClientId;
                    options.Authority                 = string.Format(loginOptions.AadInstance, loginOptions.Tenant);
                    options.SignedOutRedirectUri      = loginOptions.PostLogoutRedirectUri;
                    options.TokenValidationParameters = new TokenValidationParameters()
                    {
                        ValidateIssuer = (loginOptions.Tenant != "common")
                    };
                    options.Events = new OpenIdConnectEvents
                    {
                        OnRemoteFailure = context =>
                        {
                            context.HandleResponse();
                            context.Response.Redirect("/error");
                            return(Task.CompletedTask);
                        },
                        OnRedirectToIdentityProvider = context =>
                        {
                            var message = context.ProtocolMessage;
                            if (!string.IsNullOrEmpty(message.State))
                            {
                                context.Properties.Items[OpenIdConnectDefaults.UserstatePropertiesKey] = message.State;
                            }

                            message.State = context.Options.StateDataFormat.Protect(context.Properties);
                            DotvvmAuthenticationHelper.ApplyRedirectResponse(context.HttpContext, context.ProtocolMessage.BuildRedirectUrl());
                            return(Task.CompletedTask);
                        }
                    };
                });
            }
        }
コード例 #16
0
        private void ConfigureAuth(IAppBuilder app)
        {
            // we need the Cookie Authentication middleware to persist the authentication token
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                ExpireTimeSpan     = TimeSpan.FromHours(12),
                AuthenticationType = CookieAuthenticationDefaults.AuthenticationType
            });

            // set cookie authentication type as default
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            // configure Azure AD authentication
            var authority = new Uri("https://login.microsoftonline.com/" +
                                    ConfigurationManager.AppSettings["ida:TenantId"] + "/");

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                ClientId        = ConfigurationManager.AppSettings["ida:ClientId"],
                Authority       = authority.ToString(),
                MetadataAddress = new Uri(authority, ".well-known/openid-configuration").ToString(),

                TokenValidationParameters = new TokenValidationParameters
                {
                    // we cannot validate issuer in multi-tenant scenarios
                    ValidateIssuer = ConfigurationManager.AppSettings["ida:TenantId"] != "common"
                },

                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed = context =>
                    {
                        // redirect to error page if the authentication fails
                        context.OwinContext.Response.Redirect("/error");
                        context.HandleResponse();

                        return(Task.FromResult(0));
                    },

                    RedirectToIdentityProvider = context =>
                    {
                        // determines the base URL of the application (useful when the app can run on multiple domains)
                        var appBaseUrl = GetApplicationBaseUrl(context.Request);
                        context.ProtocolMessage.RedirectUri           = appBaseUrl;
                        context.ProtocolMessage.PostLogoutRedirectUri = appBaseUrl;

                        if (context.ProtocolMessage.RequestType == OpenIdConnectRequestType.AuthenticationRequest)
                        {
                            // we need to handle the redirect to the login page ourselves because redirects cannot use HTTP 302 in DotVVM
                            var redirectUri = context.ProtocolMessage.CreateAuthenticationRequestUrl();
                            DotvvmAuthenticationHelper.ApplyRedirectResponse(context.OwinContext, redirectUri);
                            context.HandleResponse();
                        }
                        else if (context.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest)
                        {
                            // we need to handle the redirect to the logout page ourselves because redirects cannot use HTTP 302 in DotVVM
                            var redirectUri = context.ProtocolMessage.CreateLogoutRequestUrl();
                            DotvvmAuthenticationHelper.ApplyRedirectResponse(context.OwinContext, redirectUri);
                            context.HandleResponse();
                        }

                        return(Task.FromResult(0));
                    },

                    SecurityTokenValidated = context =>
                    {
                        var claimsPrincipal = new ClaimsPrincipal(context.AuthenticationTicket.Identity);

                        // TODO: load custom data and add them in the claims identity (e.g. load user id, roles etc.)

                        // store the identity in the HTTP request context so it can be persisted using the Cookie authentication middleware
                        context.OwinContext.Request.User = claimsPrincipal;

                        return(Task.FromResult(0));
                    }
                }
            });
        }
コード例 #17
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddOptions();
            services.Configure <AppSettings>(Configuration.GetSection("AppSettings"));
            services.AddSingleton(Configuration);
            services.AddSingleton((IConfigurationRoot)Configuration);

            services.AddDataProtection();
            services.AddAuthorization();
            services.AddWebEncoders();

            services.AddDotVVM(options =>
            {
                options.AddDefaultTempStorages("Temp");
                options.AddMiniProfilerEventTracing();
                options.AddApplicationInsightsTracing();

                var dynamicDataConfig = new AppDynamicDataConfiguration();
                options.AddDynamicData(dynamicDataConfig);
            });

            services.AddDbContext <AppDbContext>(options =>
                                                 options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddIdentity <AppUser, AppRole>()
            .AddEntityFrameworkStores <AppDbContext>()
            .AddDefaultTokenProviders();

            services.Configure <IdentityOptions>(options =>
            {
                // Password settings
                options.Password.RequireDigit           = true;
                options.Password.RequiredLength         = 8;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = true;
                options.Password.RequireLowercase       = false;
                options.Password.RequiredUniqueChars    = 6;

                // Lockout settings
                options.Lockout.DefaultLockoutTimeSpan  = TimeSpan.FromMinutes(30);
                options.Lockout.MaxFailedAccessAttempts = 10;
                options.Lockout.AllowedForNewUsers      = true;

                // User settings
                options.User.RequireUniqueEmail = true;
            });

            services
            .AddAuthentication(AuthenticationConstants.AUTHENTICATION_TYPE_NAME)
            .AddCookie(AuthenticationConstants.AUTHENTICATION_TYPE_NAME, options =>
            {
                // Cookie settings
                options.Cookie.HttpOnly   = true;
                options.Cookie.Expiration = TimeSpan.FromDays(150);
                options.LoginPath         = new PathString("/Default3"); // If the LoginPath is not set here, ASP.NET Core will default to /Account/Login
                options.LogoutPath        = "/Account/Logout";           // If the LogoutPath is not set here, ASP.NET Core will default to /Account/Logout
                options.AccessDeniedPath  = "/Account/AccessDenied";     // If the AccessDeniedPath is not set here, ASP.NET Core will default to /Account/AccessDenied
                options.SlidingExpiration = true;
                options.Events            = new CookieAuthenticationEvents
                {
                    OnRedirectToReturnUrl    = c => DotvvmAuthenticationHelper.ApplyRedirectResponse(c.HttpContext, c.RedirectUri),
                    OnRedirectToAccessDenied = c => DotvvmAuthenticationHelper.ApplyStatusCodeResponse(c.HttpContext, 403),
                    OnRedirectToLogin        = c => DotvvmAuthenticationHelper.ApplyRedirectResponse(c.HttpContext, c.RedirectUri),
                    OnRedirectToLogout       = c => DotvvmAuthenticationHelper.ApplyRedirectResponse(c.HttpContext, c.RedirectUri)
                };
            });

            services.AddMemoryCache();

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            return(WindsorRegistrationHelper.CreateServiceProvider(InitializeWindsor(), services));
        }
コード例 #18
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddNodeServices();
            services.AddDataProtection();
            services.AddAuthorization();
            services.AddWebEncoders();
            services.AddAutoMapper();
            services.AddDotVVM(options =>
            {
                options.AddDefaultTempStorages("Temp");
            });
            services.AddOptions();
            // services.AddDataAccess<MyAppContext>();
            var configurationSection = Configuration.GetSection("ConnectionStrings:DataAccessPostgreSqlProvider").Value;

            // var configureOptions = services.BuildServiceProvider().GetRequiredService<IConfigureOptions<ConnectionStrings>>();
            services.AddDbContext <MyAppContext>(options =>
            {
                // options.UseOpenIddict();
                options.UseNpgsql(
                    configurationSection,
                    b => b.MigrationsAssembly("Electroweb")
                    );
            });


            //AUTH

            services.AddAuthentication(sharedOptions =>
            {
                sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            })
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options => {
                options.Events = new CookieAuthenticationEvents
                {
                    OnRedirectToReturnUrl    = c => DotvvmAuthenticationHelper.ApplyRedirectResponse(c.HttpContext, c.RedirectUri),
                    OnRedirectToAccessDenied = c => DotvvmAuthenticationHelper.ApplyStatusCodeResponse(c.HttpContext, 403),
                    OnRedirectToLogin        = c => DotvvmAuthenticationHelper.ApplyRedirectResponse(c.HttpContext, c.RedirectUri),
                    OnRedirectToLogout       = c => DotvvmAuthenticationHelper.ApplyRedirectResponse(c.HttpContext, c.RedirectUri)
                };
                options.LoginPath = new PathString("/login");
            });


            // Add converter to DI
            // services.AddSingleton(typeof(IConverter), new SynchronizedConverter(new PdfTools()));
            //llamar a los repositorios
            services.AddTransient <ITipoCableRepository, TipoCableRepository>();
            services.AddTransient <IDetalleTipoCableRepository, DetalleTipoCableRepository>();
            services.AddTransient <ITipoNovedadRepository, TipoNovedadRepository>();
            services.AddTransient <ITipoEquipoRepository, TipoEquipoRepository>();
            services.AddTransient <IDetalleTipoNovedadRepository, DetalleTipoNovedadRepository>();
            services.AddTransient <IEmpresaRepository, EmpresaRepository>();
            services.AddTransient <IDispositivoRepository, DispositivoRepository>();
            services.AddTransient <IEmpresaRepository, EmpresaRepository>();
            services.AddTransient <ICiudadRepository, CiudadRepository>();
            services.AddTransient <IDepartamentoRepository, DepartamentoRepository>();
            services.AddTransient <IMaterialRepository, MaterialRepository>();
            services.AddTransient <IEstadoRepository, EstadoRepository>();
            services.AddTransient <IElementoRepository, ElementoRepository>();
            services.AddTransient <IElementoCableRepository, ElementoCableRepository>();
            services.AddTransient <IEquipoElementoRepository, EquipoElementoRepository>();
            services.AddTransient <ILongitudElementoRepository, LongitudElementoRepository>();

            services.AddTransient <INovedadRepository, NovedadRepository>();
            services.AddTransient <IFotoRepository, FotoRepository>();
            services.AddTransient <IUsuarioRepository, UsuarioRepository>();

            services.AddTransient <IPerdidaRepository, PerdidaRepository>();
            //Ciudad Empresa
            services.AddTransient <ICiudad_EmpresaRepository, Ciudad_EmpresaRepository>();

            services.AddTransient <ILocalizacionElementoRepository, LocalizacionElementoRepository>();

            services.AddScoped <MasterDetailsPdfReport>();
            services.AddDirectoryBrowser();
            //agregar todo las interaces y sus implementacions
            IServiceProvider serviceProvider = services.BuildServiceProvider();

            // var context = serviceProvider.GetRequiredService<MyAppContext>();
            var masterdetail  = serviceProvider.GetRequiredService <MasterDetailsPdfReport>();
            var elemntservice = serviceProvider.GetRequiredService <IElementoRepository>();

            MasterDetailsPdfReport._IelementosRepository = elemntservice;
            //  DbInitializer.Initialize(context);

            //  string wwwroot=Path.Combine("wwwroot");
            // string TheUrl = "http://54.86.105.4/";
            // string remote = GetHtmlPage(TheUrl);

            //  MasterDetailsPdfReport.CreateMasterDetailsPdfReport(wwwroot);
        }