Exemplo n.º 1
0
        public void Configuration(IAppBuilder app)
        {
            AppDomain.CurrentDomain.AssemblyResolve += CurrentDomainOnAssemblyResolve;

            const string modulesVirtualPath  = "~/Modules";
            var          modulesPhysicalPath = HostingEnvironment.MapPath(modulesVirtualPath).EnsureEndSeparator();

            var bootstraper = new VirtoCommercePlatformWebBootstraper(modulesVirtualPath, modulesPhysicalPath, _assembliesPath);

            bootstraper.Run();

            var container = bootstraper.Container;

            container.RegisterInstance(app);

            var moduleCatalog = container.Resolve <IModuleCatalog>();

            // Register URL rewriter before modules initialization
            if (Directory.Exists(modulesPhysicalPath))
            {
                var applicationBase     = AppDomain.CurrentDomain.SetupInformation.ApplicationBase.EnsureEndSeparator();
                var modulesRelativePath = MakeRelativePath(applicationBase, modulesPhysicalPath);

                var urlRewriterOptions       = new UrlRewriterOptions();
                var moduleInitializerOptions = (ModuleInitializerOptions)container.Resolve <IModuleInitializerOptions>();
                moduleInitializerOptions.SampleDataLevel = EnumUtility.SafeParse(ConfigurationManager.AppSettings["VirtoCommerce:SampleDataLevel"], SampleDataLevel.None);

                foreach (var module in moduleCatalog.Modules.OfType <ManifestModuleInfo>())
                {
                    var urlRewriteKey   = string.Format(CultureInfo.InvariantCulture, "/Modules/$({0})", module.ModuleName);
                    var urlRewriteValue = MakeRelativePath(modulesPhysicalPath, module.FullPhysicalPath);
                    urlRewriterOptions.Items.Add(PathString.FromUriComponent(urlRewriteKey), "/" + urlRewriteValue);

                    moduleInitializerOptions.ModuleDirectories.Add(module.ModuleName, module.FullPhysicalPath);
                }

                app.Use <UrlRewriterOwinMiddleware>(urlRewriterOptions);
                app.UseStaticFiles(new StaticFileOptions
                {
                    FileSystem = new Microsoft.Owin.FileSystems.PhysicalFileSystem(modulesRelativePath)
                });
            }

            //Initialize Platform dependencies
            const string connectionStringName = "VirtoCommerce";

            InitializePlatform(container, connectionStringName);

            // Ensure all modules are loaded
            var moduleManager = container.Resolve <IModuleManager>();

            foreach (var module in moduleCatalog.Modules.Where(x => x.State == ModuleState.NotStarted))
            {
                moduleManager.LoadModule(module.ModuleName);
            }

            // Post-initialize
            var authenticationOptions = new AuthenticationOptions
            {
                CookiesEnabled             = GetAppSettingsValue("VirtoCommerce:Authentication:Cookies.Enabled", true),
                CookiesValidateInterval    = GetAppSettingsValue("VirtoCommerce:Authentication:Cookies.ValidateInterval", TimeSpan.FromHours(24)),
                BearerTokensEnabled        = GetAppSettingsValue("VirtoCommerce:Authentication:BearerTokens.Enabled", true),
                BearerTokensExpireTimeSpan = GetAppSettingsValue("VirtoCommerce:Authentication:BearerTokens.AccessTokenExpireTimeSpan", TimeSpan.FromHours(1)),
                HmacEnabled = GetAppSettingsValue("VirtoCommerce:Authentication:Hmac.Enabled", true),
                HmacSignatureValidityPeriod = GetAppSettingsValue("VirtoCommerce:Authentication:Hmac.SignatureValidityPeriod", TimeSpan.FromMinutes(20)),
                ApiKeysEnabled                  = GetAppSettingsValue("VirtoCommerce:Authentication:ApiKeys.Enabled", true),
                ApiKeysHttpHeaderName           = GetAppSettingsValue("VirtoCommerce:Authentication:ApiKeys.HttpHeaderName", "api_key"),
                ApiKeysQueryStringParameterName = GetAppSettingsValue("VirtoCommerce:Authentication:ApiKeys.QueryStringParameterName", "api_key"),
            };

            OwinConfig.Configure(app, container, connectionStringName, authenticationOptions);

            var jobScheduler = container.Resolve <SendNotificationsJobsSheduler>();

            jobScheduler.SheduleJobs();

            var notificationManager = container.Resolve <INotificationManager>();

            notificationManager.RegisterNotificationType(() => new RegistrationEmailNotification(container.Resolve <IEmailNotificationSendingGateway>())
            {
                DisplayName          = "Registration notification",
                Description          = "This notification sends by email to client when he finish registration",
                NotificationTemplate = new NotificationTemplate
                {
                    Body     = PlatformNotificationResource.RegistrationNotificationBody,
                    Subject  = PlatformNotificationResource.RegistrationNotificationSubject,
                    Language = "en-US"
                }
            });

            var postInitializeModules = moduleCatalog.CompleteListWithDependencies(moduleCatalog.Modules)
                                        .Where(m => m.ModuleInstance != null)
                                        .ToArray();

            foreach (var module in postInitializeModules)
            {
                moduleManager.PostInitializeModule(module);
            }

            var hubConfiguration = new HubConfiguration();

            hubConfiguration.EnableJavaScriptProxies = false;
            app.MapSignalR(hubConfiguration);
        }
Exemplo n.º 2
0
        public static void Configure(IAppBuilder app, IUnityContainer container, string databaseConnectionStringName, AuthenticationOptions authenticationOptions)
        {
            // Configure the db context, user manager and role manager to use a single instance per request
            app.CreatePerOwinContext(() => new SecurityDbContext(databaseConnectionStringName));
            app.CreatePerOwinContext <ApplicationUserStore>(ApplicationUserStore.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create);

            if (authenticationOptions.CookiesEnabled)
            {
                // Enable the application to use a cookie to store information for the signed in user
                // and to use a cookie to temporarily store information about a user logging in with a third party login provider
                // Configure the sign in cookie
                app.UseCookieAuthentication(new CookieAuthenticationOptions
                {
                    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                    //LoginPath = new PathString("/Account/Logon"),
                    Provider = new CookieAuthenticationProvider
                    {
                        // Enables the application to validate the security stamp when the user logs in.
                        // This is a security feature which is used when you change a password or add an external login to your account.
                        OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, ApplicationUser>(
                            validateInterval: authenticationOptions.CookiesValidateInterval,
                            regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                    }
                });
            }

            if (authenticationOptions.BearerTokensEnabled)
            {
                app.UseOAuthBearerTokens(new OAuthAuthorizationServerOptions
                {
                    TokenEndpointPath     = new PathString("/Token"),
                    AuthorizeEndpointPath = new PathString("/Account/Authorize"),
                    Provider = new ApplicationOAuthProvider(PublicClientId),
                    AccessTokenExpireTimeSpan = authenticationOptions.BearerTokensExpireTimeSpan,
                    AllowInsecureHttp         = true
                });
            }

            if (authenticationOptions.HmacEnabled || authenticationOptions.ApiKeysEnabled)
            {
                var apiAccountProvider     = container.Resolve <IApiAccountProvider>();
                var claimsIdentityProvider = container.Resolve <IClaimsIdentityProvider>();
                var cacheManager           = container.Resolve <CacheManager>();

                var cacheSettings = new[]
                {
                    new CacheSettings(HmacAuthenticationHandler.CacheGroup, TimeSpan.FromSeconds(60))
                };
                cacheManager.AddCacheSettings(cacheSettings);

                if (authenticationOptions.HmacEnabled)
                {
                    app.UseHmacAuthentication(new HmacAuthenticationOptions
                    {
                        ApiCredentialsProvider  = apiAccountProvider,
                        IdentityProvider        = claimsIdentityProvider,
                        CacheManager            = cacheManager,
                        SignatureValidityPeriod = authenticationOptions.HmacSignatureValidityPeriod
                    });
                }

                if (authenticationOptions.ApiKeysEnabled)
                {
                    app.UseApiKeysAuthentication(new ApiKeysAuthenticationOptions
                    {
                        ApiCredentialsProvider   = apiAccountProvider,
                        IdentityProvider         = claimsIdentityProvider,
                        CacheManager             = cacheManager,
                        HttpHeaderName           = authenticationOptions.ApiKeysHttpHeaderName,
                        QueryStringParameterName = authenticationOptions.ApiKeysQueryStringParameterName
                    });
                }
            }

            var permissionService = container.Resolve <IPermissionService>();

            app.UseHangfire(config =>
            {
                config.UseUnityActivator(container);
                config.UseSqlServerStorage(databaseConnectionStringName, new SqlServerStorageOptions {
                    PrepareSchemaIfNecessary = false, QueuePollInterval = TimeSpan.FromSeconds(60)                                                                                    /* 15 Default value */
                });
                config.UseAuthorizationFilters(new PermissionBasedAuthorizationFilter(permissionService)
                {
                    Permission = PredefinedPermissions.BackgroundJobsManage
                });
                config.UseServer();
            });
        }
Exemplo n.º 3
0
        public void Configuration(IAppBuilder app, string virtualRoot, string routPrefix)
        {
            VirtualRoot = virtualRoot;

            _assembliesPath = HostingEnvironment.MapPath(VirtualRoot + "/App_Data/Modules");
            var modulesVirtualPath  = VirtualRoot + "/Modules";
            var modulesPhysicalPath = HostingEnvironment.MapPath(modulesVirtualPath).EnsureEndSeparator();

            AppDomain.CurrentDomain.AssemblyResolve += CurrentDomainOnAssemblyResolve;

            //Modules initialization
            var bootstrapper = new VirtoCommercePlatformWebBootstrapper(modulesVirtualPath, modulesPhysicalPath, _assembliesPath);

            bootstrapper.Run();

            var container = bootstrapper.Container;

            container.RegisterInstance(app);

            var moduleInitializerOptions = (ModuleInitializerOptions)container.Resolve <IModuleInitializerOptions>();

            moduleInitializerOptions.VirtualRoot = virtualRoot;
            moduleInitializerOptions.RoutPrefix  = routPrefix;

            //Initialize Platform dependencies
            const string connectionStringName = "VirtoCommerce";

            InitializePlatform(app, container, connectionStringName);

            var moduleManager = container.Resolve <IModuleManager>();
            var moduleCatalog = container.Resolve <IModuleCatalog>();

            var applicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase.EnsureEndSeparator();

            // Register URL rewriter for platform scripts
            var scriptsPhysicalPath        = HostingEnvironment.MapPath(VirtualRoot + "/Scripts").EnsureEndSeparator();
            var scriptsRelativePath        = MakeRelativePath(applicationBase, scriptsPhysicalPath);
            var platformUrlRewriterOptions = new UrlRewriterOptions();

            platformUrlRewriterOptions.Items.Add(PathString.FromUriComponent("/$(Platform)/Scripts"), "");
            app.Use <UrlRewriterOwinMiddleware>(platformUrlRewriterOptions);
            app.UseStaticFiles(new StaticFileOptions
            {
                FileSystem = new Microsoft.Owin.FileSystems.PhysicalFileSystem(scriptsRelativePath)
            });

            // Register URL rewriter before modules initialization
            if (Directory.Exists(modulesPhysicalPath))
            {
                var modulesRelativePath = MakeRelativePath(applicationBase, modulesPhysicalPath);

                var urlRewriterOptions = new UrlRewriterOptions();

                foreach (var module in moduleCatalog.Modules.OfType <ManifestModuleInfo>())
                {
                    var urlRewriteKey   = string.Format(CultureInfo.InvariantCulture, "/Modules/$({0})", module.ModuleName);
                    var urlRewriteValue = MakeRelativePath(modulesPhysicalPath, module.FullPhysicalPath);
                    urlRewriterOptions.Items.Add(PathString.FromUriComponent(urlRewriteKey), "/" + urlRewriteValue);

                    moduleInitializerOptions.ModuleDirectories.Add(module.ModuleName, module.FullPhysicalPath);
                }

                app.Use <UrlRewriterOwinMiddleware>(urlRewriterOptions);
                app.UseStaticFiles(new StaticFileOptions
                {
                    FileSystem = new Microsoft.Owin.FileSystems.PhysicalFileSystem(modulesRelativePath)
                });
            }

            // Ensure all modules are loaded
            foreach (var module in moduleCatalog.Modules.Where(x => x.State == ModuleState.NotStarted))
            {
                moduleManager.LoadModule(module.ModuleName);
            }

            // Post-initialize

            // Platform MVC configuration
            if (IsApplication)
            {
                AreaRegistration.RegisterAllAreas();
            }

            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();

            // Security OWIN configuration
            var authenticationOptions = new AuthenticationOptions
            {
                CookiesEnabled             = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:Authentication:Cookies.Enabled", true),
                CookiesValidateInterval    = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:Authentication:Cookies.ValidateInterval", TimeSpan.FromDays(1)),
                BearerTokensEnabled        = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:Authentication:BearerTokens.Enabled", true),
                BearerTokensExpireTimeSpan = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:Authentication:BearerTokens.AccessTokenExpireTimeSpan", TimeSpan.FromHours(1)),
                HmacEnabled = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:Authentication:Hmac.Enabled", true),
                HmacSignatureValidityPeriod = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:Authentication:Hmac.SignatureValidityPeriod", TimeSpan.FromMinutes(20)),
                ApiKeysEnabled                  = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:Authentication:ApiKeys.Enabled", true),
                ApiKeysHttpHeaderName           = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:Authentication:ApiKeys.HttpHeaderName", "api_key"),
                ApiKeysQueryStringParameterName = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:Authentication:ApiKeys.QueryStringParameterName", "api_key"),
            };

            OwinConfig.Configure(app, container, connectionStringName, authenticationOptions);

            RecurringJob.AddOrUpdate <SendNotificationsJobs>("SendNotificationsJob", x => x.Process(), "*/1 * * * *");

            var notificationManager = container.Resolve <INotificationManager>();

            notificationManager.RegisterNotificationType(() => new RegistrationEmailNotification(container.Resolve <IEmailNotificationSendingGateway>())
            {
                DisplayName          = "Registration notification",
                Description          = "This notification sends by email to client when he finish registration",
                NotificationTemplate = new NotificationTemplate
                {
                    Body     = PlatformNotificationResource.RegistrationNotificationBody,
                    Subject  = PlatformNotificationResource.RegistrationNotificationSubject,
                    Language = "en-US"
                }
            });

            var postInitializeModules = moduleCatalog.CompleteListWithDependencies(moduleCatalog.Modules)
                                        .Where(m => m.ModuleInstance != null)
                                        .ToArray();

            foreach (var module in postInitializeModules)
            {
                moduleManager.PostInitializeModule(module);
            }

            var hubConfiguration = new HubConfiguration();

            hubConfiguration.EnableJavaScriptProxies = false;
            app.MapSignalR("/" + moduleInitializerOptions.RoutPrefix + "signalr", hubConfiguration);
        }
Exemplo n.º 4
0
        public static void Configure(IAppBuilder app, IUnityContainer container, AuthenticationOptions authenticationOptions)
        {
            app.CreatePerOwinContext(() => container.Resolve <SecurityDbContext>());
            app.CreatePerOwinContext(() => container.Resolve <ApplicationUserManager>());

            app.UseCors(CorsOptions.AllowAll);

            if (authenticationOptions.CookiesEnabled)
            {
                // Enable the application to use a cookie to store information for the signed in user
                // and to use a cookie to temporarily store information about a user logging in with a third party login provider
                // Configure the sign in cookie
                app.UseCookieAuthentication(new CookieAuthenticationOptions
                {
                    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                    //LoginPath = new PathString("/Account/Logon"),
                    Provider = new CookieAuthenticationProvider
                    {
                        // Enables the application to validate the security stamp when the user logs in.
                        // This is a security feature which is used when you change a password or add an external login to your account.
                        OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, ApplicationUser>(
                            validateInterval: authenticationOptions.CookiesValidateInterval,
                            regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                    }
                });
            }

            if (authenticationOptions.BearerTokensEnabled)
            {
                app.UseOAuthBearerTokens(new OAuthAuthorizationServerOptions
                {
                    TokenEndpointPath     = new PathString("/Token"),
                    AuthorizeEndpointPath = new PathString("/Account/Authorize"),
                    Provider = new ApplicationOAuthProvider(PublicClientId),
                    AccessTokenExpireTimeSpan = authenticationOptions.BearerTokensExpireTimeSpan,
                    AllowInsecureHttp         = true
                });
            }

            if (authenticationOptions.HmacEnabled || authenticationOptions.ApiKeysEnabled)
            {
                var apiAccountProvider     = container.Resolve <IApiAccountProvider>();
                var claimsIdentityProvider = container.Resolve <IClaimsIdentityProvider>();
                var cacheManager           = container.Resolve <ICacheManager <object> >();

                if (authenticationOptions.HmacEnabled)
                {
                    app.UseHmacAuthentication(new HmacAuthenticationOptions
                    {
                        ApiCredentialsProvider  = apiAccountProvider,
                        IdentityProvider        = claimsIdentityProvider,
                        CacheManager            = cacheManager,
                        SignatureValidityPeriod = authenticationOptions.HmacSignatureValidityPeriod
                    });
                }

                if (authenticationOptions.ApiKeysEnabled)
                {
                    app.UseApiKeysAuthentication(new ApiKeysAuthenticationOptions
                    {
                        ApiCredentialsProvider   = apiAccountProvider,
                        IdentityProvider         = claimsIdentityProvider,
                        CacheManager             = cacheManager,
                        HttpHeaderName           = authenticationOptions.ApiKeysHttpHeaderName,
                        QueryStringParameterName = authenticationOptions.ApiKeysQueryStringParameterName
                    });
                }
            }

            app.Use <CurrentUserOwinMiddleware>(container.Resolve <Func <ICurrentUser> >());
        }