Esempio n. 1
0
        public void Configuration(IAppBuilder app)
        {
            DataProtectionProvider = app.GetDataProtectionProvider();

            app.CreatePerOwinContext(() => DependencyResolver.Current.GetService<MendotaContext>());
            app.CreatePerOwinContext(() => DependencyResolver.Current.GetService<MendotaUserManager>());
            app.CreatePerOwinContext(() => DependencyResolver.Current.GetService<MendotaSignInManager>());

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                CookieHttpOnly = true,
                CookieName = "Mendota",
                ExpireTimeSpan = TimeSpan.FromDays(14),
                LoginPath = new PathString("/Account/Login"),
                LogoutPath = new PathString("/Account/Logout"),
                ReturnUrlParameter = "ReturnUrl",
                SlidingExpiration = true,
                Provider = new CookieAuthenticationProvider
                {
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<MendotaUserManager, User, int>(
                        validateInterval: TimeSpan.FromMinutes(2),
                        regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager),
                        getUserIdCallback: (id) => (id.GetUserId<int>()))
                }
            });

            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(10));
        }
Esempio n. 2
0
        public static IComponentContext RegisterDependancies(IAppBuilder app)
        {
            var builder = new ContainerBuilder();

            // REGISTER DEPENDENCIES
            builder.RegisterType<ApplicationDbContext>().As<DbContext>();
            builder.RegisterType<ApplicationUserStore>().As<IUserStore<ApplicationUser>>();
            builder.RegisterType<ApplicationUserManager>().AsSelf();
            builder.RegisterType<ApplicationSignInManager>().AsSelf();
            builder.Register<IAuthenticationManager>(c => HttpContext.Current.GetOwinContext().Authentication);
            builder.Register<IDataProtectionProvider>(c => app.GetDataProtectionProvider());

            // register mvc controllers
            builder.RegisterControllers(typeof(MvcApplication).Assembly);

            // register webapi controller
            builder.RegisterApiControllers(typeof(MvcApplication).Assembly);

            builder.RegisterGeneric(typeof(DataRepository<>)).As(typeof(IDataRepository<>));

            var container = builder.Build();

            // replace mvc dependancy resolver with autofac
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            // replace webapi dependancy resolver with autofac
            GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);

            return container;
        }
Esempio n. 3
0
        public void Configuration(IAppBuilder app)
        {
            var builder = new ContainerBuilder();
            var assemblies = BuildManager.GetReferencedAssemblies().Cast<Assembly>().ToArray();

            builder.RegisterType<Entities>().As<IDbContext>().InstancePerLifetimeScope();
            builder.RegisterType<ApplicationDbContext>().AsSelf().InstancePerLifetimeScope();

            builder.RegisterAssemblyTypes(typeof(IRepository<>).Assembly).AsClosedTypesOf(typeof(IRepository<>)).InstancePerRequest();

            builder.RegisterAssemblyTypes(ServiceAssembly).Where(type => typeof(ServiceBase).IsAssignableFrom(type) && !type.IsAbstract).AsImplementedInterfaces().InstancePerRequest();
            builder.RegisterAssemblyTypes(MapperAssembly).Where(type => typeof(MapperBase).IsAssignableFrom(type) && !type.IsAbstract).AsImplementedInterfaces().InstancePerRequest();

            builder.RegisterType<ApplicationUserStore>().As<IUserStore<ApplicationUser>>().InstancePerRequest();
            builder.RegisterType<ApplicationUserManager>().AsSelf().InstancePerRequest();
            builder.RegisterType<ApplicationSignInManager>().AsSelf().InstancePerRequest();
            builder.RegisterType<RoleStore<IdentityRole>>().As<IRoleStore<IdentityRole, string>>().InstancePerRequest();
            builder.RegisterType<ApplicationRoleManager>().AsSelf().InstancePerRequest();
            builder.Register(c => HttpContext.Current.GetOwinContext().Authentication).InstancePerRequest();
            builder.Register(c => app.GetDataProtectionProvider()).InstancePerRequest();

            builder.RegisterModule(new LoggingModule());

            builder.RegisterControllers(assemblies);

            var container = builder.Build();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            app.UseAutofacMiddleware(container);
            app.UseAutofacMvc();

            ConfigureAuth(app);
        }
Esempio n. 4
0
        private static void RegisterIdentity(IAppBuilder app, ContainerBuilder builder)
        {
            builder.RegisterType<UserStore<User>>()
                .As<IUserStore<User, string>>()
                .As<IUserStore<User>>()
                .InstancePerLifetimeScope();

            builder.RegisterType<UserManager<User, string>>()
                .AsSelf()
                .InstancePerRequest();

            builder.RegisterType<UserManager<User>>()
                .AsSelf()
                .InstancePerRequest();

            builder.RegisterType<SignInManager<User, string>>()
                .AsSelf()
                .InstancePerRequest();

            builder.Register(c => HttpContext.Current.GetOwinContext().Authentication)
                .AsImplementedInterfaces()
                .InstancePerRequest();

            builder.Register<IAuthenticationManager>(c => HttpContext.Current.GetOwinContext().Authentication)
                .InstancePerRequest();
            builder.Register<IDataProtectionProvider>(c => app.GetDataProtectionProvider())
                .InstancePerRequest();
        }
Esempio n. 5
0
    public void Configuration(IAppBuilder app)
    {
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Login")
        });

        DataProtectionProvider = app.GetDataProtectionProvider();

        //HttpConfiguration config = new HttpConfiguration();
        //config.MapHttpAttributeRoutes();

        ////config.Routes.MapHttpRoute(
        ////    name: "DefaultApi",
        ////    routeTemplate: "api/{controller}/{id}",
        ////    defaults: new { id = RouteParameter.Optional }
        ////);

        //app.UseWebApi(config);

        ImageResizer.Configuration.Config.Current.Pipeline.RewriteDefaults +=
            delegate(IHttpModule m, HttpContext c, ImageResizer.Configuration.IUrlEventArgs args)
            {
                if (args.VirtualPath.IndexOf("/images/", StringComparison.OrdinalIgnoreCase) > -1)
                    args.QueryString["404"] = "~/images/404.png";
            };
    }
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            DataProtectionProvider = app.GetDataProtectionProvider();
            // Enable the application to use a cookie to store information for the signed in user
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login")
            });
            // Use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Uncomment the following lines to enable logging in with third party login providers
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //   consumerKey: "",
            //   consumerSecret: "");

            //app.UseFacebookAuthentication(
            //   appId: "",
            //   appSecret: "");

            //app.UseGoogleAuthentication();
        }
Esempio n. 7
0
        public void Configuration(IAppBuilder app)
        {
            var builder = new ContainerBuilder();

            // REGISTER DEPENDENCIES
            builder.RegisterType<OnlineLibDbContext>().AsSelf().InstancePerRequest();
            builder.RegisterType<LibRoleStore>().As<IRoleStore<LibRole, Guid>>().InstancePerRequest();
            builder.RegisterType<LibUserStore>().As<IUserStore<LibUser, Guid>>().InstancePerRequest();
            builder.RegisterType<LibUserManager>().AsSelf().InstancePerRequest();
            builder.RegisterType<LinRoleManager>().AsSelf().InstancePerRequest();
            builder.RegisterType<LibSignInManager>().AsSelf().InstancePerRequest();
            builder.Register(c => HttpContext.Current.GetOwinContext().Authentication).InstancePerRequest();
            builder.Register(c => app.GetDataProtectionProvider()).InstancePerRequest();
            builder.RegisterType<LibraryRepository>().As<ILibraryRepository>().InstancePerRequest();
            builder.RegisterType<BooksRepository>().As<IBooksRepository>().InstancePerRequest();
            builder.RegisterType<EmailService>().As<IIdentityMessageService>().InstancePerRequest();

            // REGISTER CONTROLLERS
               // builder.RegisterControllers<AccountController>(typeof (ILibraryRepository)).AsSelf().InstancePerRequest();
            builder.RegisterControllers(typeof (MvcApplication).Assembly);

            // BUILD CONTAINER
            var container = builder.Build();

            // SET AUTOFAC DEPENDENCY RESOLVER
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            // REGISTER AUTOFAC WITH OWIN
            app.UseAutofacMiddleware(container);
            app.UseAutofacMvc();

            ConfigureAuth(app);
        }
Esempio n. 8
0
        public void Configuration(IAppBuilder app)
        {
            var builder = new ContainerBuilder();

            // REGISTER DEPENDENCIES
            builder.RegisterType<ApplicationDbContext>().AsSelf().InstancePerRequest();
            builder.RegisterType<ApplicationUserStore>().As<IUserStore<ApplicationUser>>().InstancePerRequest();
            builder.RegisterType<ApplicationUserManager>().AsSelf().InstancePerRequest();
            builder.RegisterType<ApplicationSignInManager>().AsSelf().InstancePerRequest();
            builder.Register<IAuthenticationManager>(c => HttpContext.Current.GetOwinContext().Authentication).InstancePerRequest();
            builder.Register<IDataProtectionProvider>(c => app.GetDataProtectionProvider()).InstancePerRequest();

            // REGISTER CONTROLLERS SO DEPENDENCIES ARE CONSTRUCTOR INJECTED
            builder.RegisterControllers(typeof(MvcApplication).Assembly);

            // BUILD THE CONTAINER
            var container = builder.Build();

            // REPLACE THE MVC DEPENDENCY RESOLVER WITH AUTOFAC
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            // REGISTER WITH OWIN
            app.UseAutofacMiddleware(container);
            app.UseAutofacMvc();

            ConfigureAuth(app);
        }
Esempio n. 9
0
        public void Configuration(IAppBuilder app)
        {
            HttpConfiguration config = new HttpConfiguration();

            //app.CreateDataProtector("ASP.NET Identity");

            // Configure OAuth
            AuthConfig.ConfigureOAuthTokenGeneration(app);




            //  Configure Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
            jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            app.UseWebApi(config);
            IDataProtectionProvider pro = app.GetDataProtectionProvider();
            Console.WriteLine("Started");
        }
Esempio n. 10
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        /// <summary>
        ///     Configures the authentication used by Veil
        /// </summary>
        /// <param name="app">
        ///     The <see cref="IAppBuilder"/> to configure
        /// </param>
        public void ConfigureAuth(IAppBuilder app)
        {
            // Setup Unity to Configure IDataProtectionProvider for the VeilUserManager constructor
            UnityConfig.GetConfiguredContainer().RegisterInstance(app.GetDataProtectionProvider());

            IGuidUserIdGetter idGetter = UnityConfig.GetConfiguredContainer().Resolve<IGuidUserIdGetter>();

            // 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/Login"),
                    ReturnUrlParameter = "returnUrl",
                    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<VeilUserManager, User, Guid>(
                                validateInterval: TimeSpan.FromMinutes(10),
                                regenerateIdentityCallback:
                                    (manager, user) => user.GenerateUserIdentityAsync(manager),
                                getUserIdCallback: identity => idGetter.GetUserId(identity))
                    }
                });
        }
Esempio n. 11
0
        public void Configuration(IAppBuilder app)
        {
            app.CreatePerOwinContext<DbContext>(() => DependencyResolver.Current.GetService<DbContext>());
            app.CreatePerOwinContext<UserManager<User, int>>(() => DependencyResolver.Current.GetService<UserManager<User, int>>());
            app.CreatePerOwinContext<SignInManager<User, int>>(() => DependencyResolver.Current.GetService<SignInManager<User, int>>());

            DataProtectionProvider = app.GetDataProtectionProvider();

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                CookieHttpOnly = true,
                CookieName = "Badger",
                ExpireTimeSpan = TimeSpan.FromDays(30),
                LoginPath = new PathString("/Account/SignIn"),
                LogoutPath = new PathString("/Account/SignOut"),
                ReturnUrlParameter = "ReturnUrl",
                SlidingExpiration = true,
                Provider = new CookieAuthenticationProvider
                {
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<UserManager<User,int>, User, int>(
                        validateInterval: TimeSpan.FromMinutes(1),
                        regenerateIdentityCallback: (manager, user) =>
                        user.GenerateUserIdentityAsync(manager),
                        getUserIdCallback: (id) => (id.GetUserId<int>()))
                }
            });
        }
Esempio n. 12
0
        private static void ConfigureAuth(IAppBuilder appBuilder)
        {
            const int twoWeeks = 14;

            ProjectObjectFactory.Container.Configure(config => config.For<IDataProtectionProvider>()
                .HybridHttpOrThreadLocalScoped()
                .Use(() => appBuilder.GetDataProtectionProvider()));

            appBuilder.CreatePerOwinContext(
                () =>ProjectObjectFactory.Container.GetInstance<ApplicationUserManager>());

            appBuilder.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login"),
                ExpireTimeSpan = TimeSpan.FromDays(twoWeeks),
                SlidingExpiration = true,
                CookieName = "decision",
                Provider = new CookieAuthenticationProvider
                {
                    OnValidateIdentity =
                            ProjectObjectFactory.Container.GetInstance<IApplicationUserManager>().OnValidateIdentity()
                }
            });

            ProjectObjectFactory.Container.GetInstance<IApplicationRoleManager>()
           .SeedDatabase();

            ProjectObjectFactory.Container.GetInstance<IApplicationUserManager>()
               .SeedDatabase();

        }
Esempio n. 13
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            DataProtectionProvider = app.GetDataProtectionProvider();

            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(() => DependencyResolver.Current.GetService<ApplicationUserManager>());

            // 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/Login"),
                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: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Enables the application to remember the second login verification factor such as phone or email.
            // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            // This is similar to the RememberMe option when you log in.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
        }
Esempio n. 14
0
        private void ConfigAutofac(IAppBuilder app)
        {
            var builder = new ContainerBuilder();
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            builder.RegisterControllers(Assembly.GetExecutingAssembly());
            builder.RegisterType<UnitOfWork>().As<IUnitOfWork>().InstancePerRequest();
            builder.RegisterType<DbFactory>().As<IDbFactory>().InstancePerRequest();
            builder.RegisterType<ShopThanhDbContext>().AsSelf().InstancePerRequest();

            //ASP Identity
            builder.RegisterType<ApplicationUserStore>().As<IUserStore<ApplicationUser>>().InstancePerRequest();
            builder.RegisterType<ApplicationUserManager>().AsSelf().InstancePerRequest();
            builder.RegisterType<ApplicationSignInManager>().AsSelf().InstancePerRequest();
            builder.Register(n => HttpContext.Current.GetOwinContext().Authentication).InstancePerRequest();
            builder.Register(n => app.GetDataProtectionProvider()).InstancePerRequest();

            //Reponsitories
            builder.RegisterAssemblyTypes(typeof(PostCategoryRepository).Assembly)
                .Where(n => n.Name.EndsWith("Repository"))
                .AsImplementedInterfaces().InstancePerRequest();

            //Services
            builder.RegisterAssemblyTypes(typeof(PostCategoryService).Assembly)
                .Where(n => n.Name.EndsWith("Service"))
                .AsImplementedInterfaces().InstancePerRequest();
            IContainer container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
            GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);
        }
Esempio n. 15
0
        public void Configuration(IAppBuilder app)
        {
            app.UseAbp();

            DataProtectionProvider = app.GetDataProtectionProvider();

            app.UseOAuthBearerAuthentication(AccountController.OAuthBearerOptions);

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login")
            });

            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            if (IsTrue("ExternalAuth.Facebook.IsEnabled"))
            {
                app.UseFacebookAuthentication(CreateFacebookAuthOptions());
            }

            if (IsTrue("ExternalAuth.Twitter.IsEnabled"))
            {
                app.UseTwitterAuthentication(CreateTwitterAuthOptions());
            }

            if (IsTrue("ExternalAuth.Google.IsEnabled"))
            {
                app.UseGoogleAuthentication(CreateGoogleAuthOptions());
            }

            app.MapSignalR();
        }
        public static void Register(IAppBuilder app, HttpConfiguration config)
        {
            var aspNetIdentityAssembly = typeof(IMarkerAspNetIdentityInterface).Assembly;
            var cornhouseCoreAssembly = typeof (IMarkerCornhouseCoreInterface).Assembly;
            var executingAssembly = Assembly.GetExecutingAssembly();
            
            var builder = new ContainerBuilder();

            builder.Register(c => InitializeRavenDb.Initialize(aspNetIdentityAssembly)).As<IDocumentStore>().InstancePerLifetimeScope();
            builder.Register(c => c.Resolve<IDocumentStore>().OpenAsyncSession()).As<IAsyncDocumentSession>().InstancePerRequest();
            builder.Register(c => HttpContext.Current.User).InstancePerRequest();

            builder.RegisterType<ApplicationUserManager>().AsSelf().InstancePerRequest();
            builder.RegisterType<ApplicationRoleManager>().AsSelf().InstancePerRequest();
            builder.RegisterType<RavenUserStore>().AsSelf().InstancePerRequest();
            builder.RegisterType<RavenRoleStore>().AsSelf().InstancePerRequest();
            

            builder.Register(c => HttpContext.Current.GetOwinContext().Authentication).InstancePerRequest();
            builder.Register(c => app.GetDataProtectionProvider()).InstancePerRequest();

            builder.RegisterApiControllers(executingAssembly);
            builder.RegisterApiControllers(aspNetIdentityAssembly);

            builder.RegisterAssemblyTypes(executingAssembly).AsImplementedInterfaces().InstancePerRequest();
            builder.RegisterAssemblyTypes(aspNetIdentityAssembly).AsImplementedInterfaces().InstancePerRequest();
            builder.RegisterAssemblyTypes(cornhouseCoreAssembly).AsImplementedInterfaces().InstancePerRequest();
            
            
            var container = builder.Build();
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

            app.UseAutofacMiddleware(container);
            app.UseAutofacWebApi(config);            
        }
Esempio n. 17
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            DataProtectionProvider = app.GetDataProtectionProvider();
            // Configure the db context and user manager to use a single instance per request
            //app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext(CreateKernel);
            app.UseNinjectMiddleware(CreateKernel);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

            // 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
            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Configure the application for OAuth based flow
            PublicClientId = "self";
            OAuthOptions = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath = new PathString("/Token"),
                Provider = new ApplicationOAuthProvider(PublicClientId),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
                AccessTokenFormat = new HunterJwtFormat("http://localhost:53147/"),
                // In production mode set AllowInsecureHttp = false
                AllowInsecureHttp = true
            };

            // Enable the application to use bearer tokens to authenticate users
            //app.UseOAuthBearerTokens(OAuthOptions);
            app.UseOAuthAuthorizationServer(OAuthOptions);
            // Uncomment the following lines to enable logging in with third party login providers
            //app.UseLinkedInAuthentication(
            //    "<YOUR API KEY>",
            //    "<YOUR SECRET KEY>"
            //    );
        }
Esempio n. 18
0
        public void Configuration(IAppBuilder app)
        {
            var builder = new ContainerBuilder();
            var config = new HttpConfiguration();

            builder.RegisterType<CustomIdentityContext>().AsSelf().InstancePerRequest();
            builder.RegisterType<Logger>().As<ILogger>().SingleInstance();

            #region AspNet.Identity IoC Registrations
            builder.RegisterType<UserRepository>().AsSelf().InstancePerRequest();
            builder.RegisterType<RoleRepository>().AsSelf().InstancePerRequest();
            builder.Register<IAuthenticationManager>(c => HttpContext.Current.GetOwinContext().Authentication).InstancePerRequest();
            builder.Register<IDataProtectionProvider>(c => app.GetDataProtectionProvider()).InstancePerRequest();

            //Register User Service
            builder.Register(c =>
                new UserService(
                    new UserRepository(
                        new CustomIdentityContext()), app.GetDataProtectionProvider()))
                        .InstancePerRequest();
            //Register Role Service
            builder.Register(c =>
                new RoleService(
                    new RoleRepository(
                        new CustomIdentityContext())))
                        .InstancePerRequest();
            //Register Sign In Service
            builder.Register(c =>
                new SignInService(
                    new UserService(
                        new UserRepository(
                            new CustomIdentityContext()), app.GetDataProtectionProvider()),
                            HttpContext.Current.GetOwinContext()
                            .Authentication));
            #endregion

            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            builder.RegisterControllers(typeof(MvcApplication).Assembly);

            var container = builder.Build();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

            app.UseAutofacMiddleware(container);
            ConfigureAuth(app);
        }
Esempio n. 19
0
        // Weitere Informationen zum Konfigurieren der Authentifizierung finden Sie unter "http://go.microsoft.com/fwlink/?LinkId=301864".
        public static void ConfigureAuth(IAppBuilder app)
        {
            // Konfigurieren des db-Kontexts, des Benutzer-Managers und des Anmelde-Managers für die Verwendung einer einzelnen Instanz pro Anforderung.
            //app.CreatePerOwinContext(MyDbContext.Create);
            //app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            //app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
            DataProtectionProvider = app.GetDataProtectionProvider();

            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(() => ServiceLocator.Current.GetInstance<ApplicationUserManager>());

            // Anwendung für die Verwendung eines Cookies zum Speichern von Informationen für den angemeldeten Benutzer aktivieren
            // und ein Cookie zum vorübergehenden Speichern von Informationen zu einem Benutzer zu verwenden, der sich mit dem Anmeldeanbieter eines Drittanbieters anmeldet.
            // Konfigurieren des Anmeldecookies.
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login"),
                Provider = new CookieAuthenticationProvider
                {
                    // Aktiviert die Anwendung für die Überprüfung des Sicherheitsstempels, wenn sich der Benutzer anmeldet.
                    // Dies ist eine Sicherheitsfunktion, die verwendet wird, wenn Sie ein Kennwort ändern oder Ihrem Konto eine externe Anmeldung hinzufügen. 

                   OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser, long>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentityCallback: (manager, user) => manager.GenerateUserIdentityAsync(user),
                        getUserIdCallback: (claim) => long.Parse(claim.GetUserId()))
                }
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Aktiviert die Anwendung für das vorübergehende Speichern von Benutzerinformationen beim Überprüfen der zweiten Stufe im zweistufigen Authentifizierungsvorgang.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Aktiviert die Anwendung für das Speichern der zweiten Anmeldeüberprüfungsstufe (z. B. Telefon oder E-Mail).
            // Wenn Sie diese Option aktivieren, wird Ihr zweiter Überprüfungsschritt während des Anmeldevorgangs auf dem Gerät gespeichert, von dem aus Sie sich angemeldet haben.
            // Dies ähnelt der RememberMe-Option bei der Anmeldung.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            // Auskommentierung der folgenden Zeilen aufheben, um die Anmeldung mit Anmeldeanbietern von Drittanbietern zu ermöglichen
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //   consumerKey: "",
            //   consumerSecret: "");

            //app.UseFacebookAuthentication(
            //   appId: "",
            //   appSecret: "");

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});
        }
 public static void ConfigureDataProtection(this TicketDeskUserManager userManager, IAppBuilder app)
 {
     //TODO: research DpapiDataProtectionProvider and figure out what the f*** this is supposed to do
     var dataProtectionProvider = app.GetDataProtectionProvider();
     if (dataProtectionProvider != null)
     {
         userManager.UserTokenProvider = new DataProtectorTokenProvider<TicketDeskUser>(dataProtectionProvider.Create("ASP.NET Identity"));
     }
 }
Esempio n. 21
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext<IdentityConnection>(() => { return new IdentityConnection(ConfigurationManager.ConnectionStrings["DatabaseConnection"]); });
            app.CreatePerOwinContext<IdentityUserManager>((options, context) =>
            {
                options.DataProtectionProvider = app.GetDataProtectionProvider();
                return IdentityUserManager.Create(options, context);
            });
            app.CreatePerOwinContext<IdentitySignInManager>(IdentitySignInManager.Create);

            // 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/Login"),
                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<IdentityUserManager, IdentityUser, Guid>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager, DefaultAuthenticationTypes.ApplicationCookie),
                        getUserIdCallback: (claim) => Guid.Parse(claim.GetUserId()))
                }
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Enables the application to remember the second login verification factor such as phone or email.
            // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            // This is similar to the RememberMe option when you log in.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            // Uncomment the following lines to enable logging in with third party login providers
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //   consumerKey: "",
            //   consumerSecret: "");

            //app.UseFacebookAuthentication(
            //   appId: "",
            //   appSecret: "");

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});
        }
Esempio n. 22
0
        private static void configureAuth(IAppBuilder app)
        {
            SmObjectFactory.Container.Configure(config =>
            {
                config.For<IDataProtectionProvider>()
                      .HybridHttpOrThreadLocalScoped()
                      .Use(() => app.GetDataProtectionProvider());
            });
            SmObjectFactory.Container.GetInstance<IApplicationUserManager>().SeedDatabase();

            // 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/Login"),
                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 = SmObjectFactory.Container.GetInstance<IApplicationUserManager>().OnValidateIdentity()
                }
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Enables the application to remember the second login verification factor such as phone or email.
            // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            // This is similar to the RememberMe option when you log in.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            app.CreatePerOwinContext(
               () => SmObjectFactory.Container.GetInstance<IApplicationUserManager>());

            // Uncomment the following lines to enable logging in with third party login providers
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //   consumerKey: "",
            //   consumerSecret: "");

            //app.UseFacebookAuthentication(
            //   appId: "",
            //   appSecret: "");

            //app.UseGoogleAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            app.MapSignalR();
        }
Esempio n. 23
0
        // Para obtener más información para configurar la autenticación, visite http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            DataProtectionProvider = app.GetDataProtectionProvider();

            // Configure el contexto de base de datos, el administrador de usuarios y el administrador de inicios de sesión para usar una única instancia por solicitud
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

            // Permitir que la aplicación use una cookie para almacenar información para el usuario que inicia sesión
            // y una cookie para almacenar temporalmente información sobre un usuario que inicia sesión con un proveedor de inicio de sesión de terceros
            // Configurar cookie de inicio de sesión
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login"),
                Provider = new CookieAuthenticationProvider
                {
                    // Permite a la aplicación validar la marca de seguridad cuando el usuario inicia sesión.
                    // Es una característica de seguridad que se usa cuando se cambia una contraseña o se agrega un inicio de sesión externo a la cuenta.
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Permite que la aplicación almacene temporalmente la información del usuario cuando se verifica el segundo factor en el proceso de autenticación de dos factores.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Permite que la aplicación recuerde el segundo factor de verificación de inicio de sesión, como el teléfono o correo electrónico.
            // Cuando selecciona esta opción, el segundo paso de la verificación del proceso de inicio de sesión se recordará en el dispositivo desde el que ha iniciado sesión.
            // Es similar a la opción Recordarme al iniciar sesión.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            // Quitar los comentarios de las siguientes líneas para habilitar el inicio de sesión con proveedores de inicio de sesión de terceros
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //   consumerKey: "",
            //   consumerSecret: "");

            //app.UseFacebookAuthentication(
            //   appId: "",
            //   appSecret: "");

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});
        }
Esempio n. 24
0
        private static void ConfigureAuthInternal(IAppBuilder app)
        {
            var container = UnityConfig.GetConfiguredContainer();

            container.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(new HierarchicalLifetimeManager());
            container.RegisterType<IdentityContext, ApplicationIdentityContext>(new HierarchicalLifetimeManager());
            container.RegisterType<ApplicationUserManager>(new HierarchicalLifetimeManager());
            container.RegisterInstance(app.GetDataProtectionProvider(), new HierarchicalLifetimeManager());

            var provider = container.Resolve<ApplicationOAuthProvider>();
            app.ConfigureAuth(provider);
        }
Esempio n. 25
0
        public void Configuration(IAppBuilder app)
        {
            dataProtectionProvider = app.GetDataProtectionProvider();

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login"),
                CookieName = "CloudCentreApp",
                //ExpireTimeSpan = System.TimeSpan.FromMinutes(10)
            });
        }
Esempio n. 26
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {

            DataProtectionProvider = app.GetDataProtectionProvider();

            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(() => DependencyResolver.Current.GetService<ApplicationUserManager>());

            // 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/Login"),
                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: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Enables the application to remember the second login verification factor such as phone or email.
            // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            // This is similar to the RememberMe option when you log in.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            // Uncomment the following lines to enable logging in with third party login providers
            app.UseMicrosoftAccountAuthentication(
                clientId: "000000004013A8D8",
                clientSecret: "5WdUBURuFxFwMa9v97z-qbEXzvq42Nf9");

            app.UseTwitterAuthentication(
               consumerKey: "0000000044116236",
               consumerSecret: "nLut0Tya491C9y9m0bdmAPrbbrnS41yJ");

            app.UseFacebookAuthentication(
               appId: "0000000044116236",
               appSecret: "nLut0Tya491C9y9m0bdmAPrbbrnS41yJ");

            app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            {
                ClientId = "654419548573-ik27lh6k0ml1r9urk6g83d9aqk3un8kl.apps.googleusercontent.com",
                ClientSecret = "GLGWXVGCiilth7kncoIMaAP0"
            });
        }
Esempio n. 27
0
        private static void ConfigureAuth(IAppBuilder appBuilder)
        {
            const int twoWeeks = 14;

            ProjectObjectFactory.Container.Configure(config => config.For<IDataProtectionProvider>()
                .HybridHttpOrThreadLocalScoped()
                .Use(() => appBuilder.GetDataProtectionProvider()));

            appBuilder.CreatePerOwinContext(
                () =>ProjectObjectFactory.Container.GetInstance<ApplicationUserManager>());

            appBuilder.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login"),
                ExpireTimeSpan = TimeSpan.FromDays(twoWeeks),
                SlidingExpiration = true,
                CookieName = "DotNetCms",
                Provider = new CookieAuthenticationProvider
                {
                    OnValidateIdentity =
                            ProjectObjectFactory.Container.GetInstance<IApplicationUserManager>().OnValidateIdentity()
                }
            });

            ProjectObjectFactory.Container.GetInstance<IApplicationRoleManager>()
           .SeedDatabase();

            ProjectObjectFactory.Container.GetInstance<IApplicationUserManager>()
               .SeedDatabase();

            appBuilder.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            //appBuilder.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Enables the application to remember the second login verification factor such as phone or email.
            // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            // This is similar to the RememberMe option when you log in.
            // appBuilder.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

           
            appBuilder.UseFacebookAuthentication(
               appId: "fdsfdsfs",
               appSecret: "fdfsfs");

            appBuilder.UseGoogleAuthentication(
                clientId: "fdsfsdfs",
                clientSecret: "fdsfsf");


        }
Esempio n. 28
0
        public void ConfigureAuth(IAppBuilder app)
        {
            Database.SetInitializer<ApplicationDbContext>(null);
            DataProtectionProvider = app.GetDataProtectionProvider();
            // Configure the db context, user manager and role
            // manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);

            // Enables the application to temporarily store user information when
            // they are verifying the second factor in the two-factor authentication process.
            app.UseTwoFactorSignInCookie(
                DefaultAuthenticationTypes.TwoFactorCookie,
                TimeSpan.FromMinutes(5));

            // Enables the application to remember the second login verification factor such
            // as phone or email. Once you check this option, your second step of
            // verification during the login process will be remembered on the device where
            // you logged in from. This is similar to the RememberMe option when you log in.
            app.UseTwoFactorRememberBrowserCookie(
                DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            var OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/api/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = new CustomOAuthProvider()
            };

            // Token Generation
            app.UseOAuthAuthorizationServer(OAuthServerOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

            // Uncomment the following lines to enable logging in
            // with third party login providers
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //   consumerKey: "",
            //   consumerSecret: "");

            //app.UseFacebookAuthentication(
            //   appId: "",
            //   appSecret: "");

            //app.UseGoogleAuthentication();
        }
Esempio n. 29
0
        public static IAppBuilder ConfigureDataProtectionProvider(this IAppBuilder app, IdentityServerOptions options)
        {
            if (options.DataProtector == null)
            {
                var provider = app.GetDataProtectionProvider();
                if (provider == null)
                {
                    provider = new DpapiDataProtectionProvider(Constants.PrimaryAuthenticationType);
                }

                options.DataProtector = new HostDataProtector(provider);
            }
            return(app);
        }
Esempio n. 30
0
        public void Configuration(IAppBuilder app)
        {
            HttpConfiguration httpConfig = new HttpConfiguration();

            DataProtectionProvider = app.GetDataProtectionProvider();

            app.Use(typeof(RequestTokenLogHandler));
            app.UseOAuthBearerTokens(ConfigureAuth());
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            WebApiConfig.Register(httpConfig);
            SwaggerConfig.Register(httpConfig);

            app.UseNinjectMiddleware(NinjectConfigurator.CreateKernel).UseNinjectWebApi(httpConfig);
        }
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            UnityConfig.Container.RegisterInstance(app.GetDataProtectionProvider(), new PerRequestLifetimeManager());

            // 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/Login"),
                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: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });

            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Enables the application to remember the second login verification factor such as phone or email.
            // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            // This is similar to the RememberMe option when you log in.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            // Uncomment the following lines to enable logging in with third party login providers
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //   consumerKey: "",
            //   consumerSecret: "");

            //app.UseFacebookAuthentication(
            //   appId: "",
            //   appSecret: "");

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});
        }
Esempio n. 32
0
        public void Register(ContainerBuilder builder, IAppBuilder app)
        {
            // factory options
            builder.Register(c => new IdentityFactoryOptions<ApplicationUserManager>() { DataProtectionProvider = new DpapiDataProtectionProvider("ApplicationN‌​ame") });
            builder.Register(c => new IdentityFactoryOptions<ApplicationRoleManager>() { DataProtectionProvider = new DpapiDataProtectionProvider("ApplicationN‌​ame") });

            // managers
            builder.RegisterType<ApplicationUserManager>().AsSelf().InstancePerRequest();
            builder.RegisterType<ApplicationRoleManager>().AsSelf().InstancePerRequest();
            builder.RegisterType<ApplicationSignInManager>().AsSelf().InstancePerRequest();

            builder.Register(c => HttpContext.Current.GetOwinContext().Authentication).InstancePerRequest();
            builder.Register(c => app.GetDataProtectionProvider()).InstancePerRequest();
        }
 public static void ConfigureUserService(this IdentityServerServiceFactory factory, IAppBuilder app)
 {
     factory.UserService = new Registration<IUserService, UserService>() { Mode = RegistrationMode.InstancePerHttpRequest };
     factory.Register(new Registration<ApplicationUserManager>() { Mode = RegistrationMode.InstancePerHttpRequest });
     factory.Register(new Registration<IUserStore<ApplicationUser>, ApplicationUserStore>() { Mode = RegistrationMode.InstancePerHttpRequest });
     factory.Register(new Registration<IwsIdentityContext>() { Mode = RegistrationMode.InstancePerHttpRequest });
     factory.Register(new Registration<IDataProtectionProvider>(f => app.GetDataProtectionProvider()) { Mode = RegistrationMode.InstancePerHttpRequest });
     factory.Register(new Registration<ConfigurationService>() { Mode = RegistrationMode.InstancePerHttpRequest });
     factory.Register(new Registration<IwsContext>() { Mode = RegistrationMode.InstancePerHttpRequest });
     factory.Register(new Registration<IUserContext, UserContext>() { Mode = RegistrationMode.InstancePerHttpRequest });
     factory.Register(new Registration<IAuthenticationManager>(resolver => HttpContext.Current.GetOwinContext().Authentication) { Mode = RegistrationMode.InstancePerHttpRequest });
     factory.Register(new Registration<IEventDispatcher, NullEventDispatcher>() { Mode = RegistrationMode.Singleton });
     factory.Register(new Registration<IClaimsRepository, ClaimsRepository>() { Mode = RegistrationMode.InstancePerHttpRequest });
 }
Esempio n. 34
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            DataProtectionProvider = app.GetDataProtectionProvider();

            // Google Client id & secret
            var googleClientId     = "s.googleusercontent.com";
            var googleClientSecret = "2Bh";
            // Facebook app id & secret
            var facebookAppId     = "Facebook.Api.AppId";
            var facebookAppSecret = "Facebook.Api.AppSecret";

            // Configure the db context, user manager and signin manager to use a single instance per request
            //app.CreatePerOwinContext(() => DependencyResolver.Current.GetService<ApplicationUserManager>());

            // 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/login"),
                SlidingExpiration  = true,
                //ExpireTimeSpan = 40.Minutes(),
                CookieName   = "rldi",
                CookieDomain = "xxx.co.uk",
                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: TimeSpan.FromMinutes(30),
                    //    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });

            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
            app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions
            {
                ClientId     = googleClientId,
                ClientSecret = googleClientSecret
            });
            app.UseFacebookAuthentication(new FacebookAuthenticationOptions
            {
                AppId     = facebookAppId,
                AppSecret = facebookAppSecret,
                Scope     = { "email" },
                UserInformationEndpoint = "https://graph.facebook.com/v2.4/me?fields=id,name,email,first_name,last_name"
            });
        }
Esempio n. 35
0
        private void ConfigureOAuthTokenGeneration(IAppBuilder app)
        {
            //use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseExternalSignInCookie(Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ExternalCookie);
            OAuthBearerOptions = new OAuthBearerAuthenticationOptions();

            DataProtectionProvider = app.GetDataProtectionProvider();

            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(() => DependencyResolver.Current.GetService <ApplicationUserManager>());
            app.CreatePerOwinContext(() => DependencyResolver.Current.GetService <ApplicationSignInManager>());

            OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                //For Dev enviroment only (on production should be AllowInsecureHttp = false)
                AllowInsecureHttp         = true,
                TokenEndpointPath         = new PathString("/api/oauth/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider          = new CustomOAuthProvider(),
                AccessTokenFormat = new CustomJwtFormat("http://localhost:3030/")
            };

            // Token Generation
            app.UseOAuthAuthorizationServer(OAuthServerOptions);
            app.UseOAuthBearerAuthentication(OAuthBearerOptions);

            //Configure Google External Login
            GoogleAuthOptions = new GoogleOAuth2AuthenticationOptions()
            {
                ClientId     = ConfigurationManager.AppSettings["googleClientId"],
                ClientSecret = ConfigurationManager.AppSettings["googleClientSecret"],
                Provider     = new GoogleAuthProvider()
            };
            GoogleAuthOptions.Scope.Add("https://www.googleapis.com/auth/plus.login");
            GoogleAuthOptions.Scope.Add("email");
            GoogleAuthOptions.Scope.Add("profile");
            app.UseGoogleAuthentication(GoogleAuthOptions);

            //Configure Facebook External Login
            FacebookAuthOptions = new FacebookAuthenticationOptions()
            {
                AppId     = ConfigurationManager.AppSettings["facebookClientId"],
                AppSecret = ConfigurationManager.AppSettings["facebookClientSecret"],
                Provider  = new FacebookAuthProvider()
            };

            FacebookAuthOptions.Scope.Add("email");
            app.UseFacebookAuthentication(FacebookAuthOptions);
        }
Esempio n. 36
0
        private static void InitializeUserManager(
            ApplicationUserManager manager, IAppBuilder app)
        {
            // Configure validation logic for usernames
            manager.UserValidator = new UserValidator <ApplicationUser>(manager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail             = true
            };

            // Configure validation logic for passwords
            manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength          = 6,
                RequireNonLetterOrDigit = true,
                RequireDigit            = true,
                RequireLowercase        = true,
                RequireUppercase        = true,
            };

            // Configure user lockout defaults
            manager.UserLockoutEnabledByDefault          = true;
            manager.DefaultAccountLockoutTimeSpan        = TimeSpan.FromMinutes(5);
            manager.MaxFailedAccessAttemptsBeforeLockout = 5;

            // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
            // You can write your own provider and plug it in here.
            manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider <ApplicationUser>
            {
                MessageFormat = "Your security code is {0}"
            });
            manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider <ApplicationUser>
            {
                Subject    = "Security Code",
                BodyFormat = "Your security code is {0}"
            });
            manager.EmailService = new EmailService();
            manager.SmsService   = new SmsService();

            var dataProtectionProvider =
                app.GetDataProtectionProvider();

            if (dataProtectionProvider != null)
            {
                manager.UserTokenProvider =
                    new DataProtectorTokenProvider <ApplicationUser>(
                        dataProtectionProvider.Create("ASP.NET Identity"));
            }
        }
Esempio n. 37
0
        public static IComponentContext RegisterDependancies(IAppBuilder app)
        {
            var builder = new ContainerBuilder();

            // REGISTER DEPENDENCIES
            builder.RegisterType <ApplicationDbContext>().As <DbContext>();
            builder.RegisterType <ApplicationUserStore>().As <IUserStore <ApplicationUser> >();
            builder.RegisterType <ApplicationUserManager>().AsSelf();

            builder.RegisterType <ApplicationRoleStore>().As <IRoleStore <IdentityRole, string> >();
            builder.RegisterType <ApplicationRoleManager>().AsSelf();

            builder.RegisterType <ApplicationSignInManager>().AsSelf();



            builder.Register <IAuthenticationManager>(c => HttpContext.Current.GetOwinContext().Authentication);
            builder.Register <IDataProtectionProvider>(c => app.GetDataProtectionProvider());

            // register mvc controllers
            builder.RegisterControllers(typeof(HomeController).Assembly);
            //builder.RegisterControllers(typeof(AccountController).Assembly);


            // register webapi controller
            builder.RegisterApiControllers(typeof(LeaveRequestController).Assembly);


            // register repositories
            builder.RegisterGeneric(typeof(DataRepository <>)).As(typeof(IDataRepository <>));
            builder.RegisterType <LeaveRequestRepository>().As <ILeaveRequestRepository>();
            builder.RegisterType <LeaveReviewRepository>().As <ILeaveReviewRepository>();
            builder.RegisterType <HolidayRepository>().As <IHolidayRepository>();
            builder.RegisterType <EmployeeRepository>().As <IEmployeeRepository>();
            builder.RegisterType <LeaveAllowedRepository>().As <ILeaveAllowedRepository>();
            builder.RegisterType <LeaveStatusRepository>().As <ILeaveStatusRepository>();
            builder.RegisterType <ProjectRepository>().As <IProjectRepository>();
            builder.RegisterType <EmailUtil>().As <IEmailUtil>();

            var container = builder.Build();

            // replace mvc dependancy resolver with autofac
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            // replace webapi dependancy resolver with autofac
            GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);

            return(container);
        }
Esempio n. 38
0
        public void Configuration(IAppBuilder app)
        {
            var builder = new ContainerBuilder();

            // REGISTER DEPENDENCIES
            builder.RegisterType <ApplicationDbContext>().AsSelf().InstancePerRequest();
            builder.RegisterType <ApplicationUserStore>().As <IUserStore <ApplicationUser> >().InstancePerRequest();
            builder.RegisterType <ApplicationUserManager>().AsSelf().InstancePerRequest();
            builder.RegisterType <RoleStore <IdentityRole> >().As <IRoleStore <IdentityRole, string> >().InstancePerRequest();
            builder.RegisterType <ApplicationRoleManager>().AsSelf().InstancePerRequest();
            builder.RegisterType <ApplicationSignInManager>().AsSelf().InstancePerRequest();
            builder.Register <IAuthenticationManager>(c => HttpContext.Current.GetOwinContext().Authentication).InstancePerRequest();
            builder.Register <IDataProtectionProvider>(c => app.GetDataProtectionProvider()).InstancePerRequest();


            builder.RegisterType <Auto>().As <IAuto>();
            builder.RegisterType <SalesPerson>().As <DataLibrary.ModelServices.ISalesPerson>();
            builder.RegisterType <Customer>().As <ICustomer>();
            builder.RegisterType <Payment>().As <IPayment>();
            builder.RegisterType <Sale>().As <ISale>();
            builder.RegisterType <Roles>().As <IRoles>();
            builder.RegisterType <UserSaleCommissionReport>().As <IUserSaleCommissionReport>();

            builder.RegisterType <AutoSalesViewModel>();
            builder.RegisterType <UserSaleReportViewModel>();

            builder.RegisterType <ReportDataProcessor>().As <IReportDataProcessor>();
            builder.RegisterType <SqlServerFindData>().As <ISqlServerFindData>();
            builder.RegisterType <AutoDataProcessor>().As <IAutoDataProcessor>();
            builder.RegisterType <UserDataProcessor>().As <IUserDataProcessor>();

            builder.RegisterType <SqlServerDataModification>().As <ISqlServerDataModification>();
            builder.RegisterType <SalesDataProcessor>().As <ISalesDataProcessor>();

            // REGISTER CONTROLLERS SO DEPENDENCIES ARE CONSTRUCTOR INJECTED
            builder.RegisterControllers(typeof(MvcApplication).Assembly);

            // BUILD THE CONTAINER
            var container = builder.Build();

            // REPLACE THE MVC DEPENDENCY RESOLVER WITH AUTOFAC
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            // REGISTER WITH OWIN
            app.UseAutofacMiddleware(container);
            app.UseAutofacMvc();

            ConfigureAuth(app);
        }
        private void ConfigAutofac(IAppBuilder app)
        {
            var builder = new ContainerBuilder();

            builder.RegisterControllers(Assembly.GetExecutingAssembly());
            // Đăng ký các đối tượng Controllers khi được khởi tạo, sẽ khởi tạo các type
            // Register your Web API controllers.
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); //Register WebApi Controllers

            builder.RegisterType <UnitOfWork>().As <IUnitOfWork>().InstancePerRequest();
            builder.RegisterType <DbFactory>().As <IDbFactory>().InstancePerRequest();

            builder.RegisterType <ShopDbContext>().AsSelf().InstancePerRequest();

            // ASP.Net Identity
            //Asp.net Identity
            builder.RegisterType <ApplicationUserStore>().As <IUserStore <ApplicationUser> >().InstancePerRequest();
            builder.RegisterType <ApplicationUserManager>().AsSelf().InstancePerRequest();
            builder.RegisterType <ApplicationSignInManager>().AsSelf().InstancePerRequest();
            builder.Register(c => HttpContext.Current.GetOwinContext().Authentication).InstancePerRequest();
            builder.Register(c => app.GetDataProtectionProvider()).InstancePerRequest();

            // Repositories
            builder.RegisterAssemblyTypes(typeof(PostCategoryRepository).Assembly)
            .Where(t => t.Name.EndsWith("Repository"))
            .AsImplementedInterfaces().InstancePerRequest();

            // Services
            builder.RegisterAssemblyTypes(typeof(PostCategoryService).Assembly)
            .Where(t => t.Name.EndsWith("Service"))
            .AsImplementedInterfaces().InstancePerRequest();


            builder.RegisterType(typeof(PostCategoryRepository));

            builder.RegisterType(typeof(PostCategoryService));

            builder.RegisterType(typeof(ErrorRepository));


            builder.RegisterType(typeof(ErrorService));



            Autofac.IContainer container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver((IContainer)container); //Set the WebApi DependencyResolver
        }
Esempio n. 40
0
        private void RegisterAspNetIdentityComponents(ContainerBuilder containerBuilder, IAppBuilder app)
        {
            containerBuilder.RegisterType <ManageUsersDbContext>().AsSelf().InstancePerLifetimeScope();

            containerBuilder
            .RegisterType <UserStore <TRUser> >()
            .As <IUserStore <TRUser> >()
            .WithParameter((pi, ctx) => pi.ParameterType == typeof(DbContext), (pi, ctx) => ctx.Resolve <ManageUsersDbContext>())
            .InstancePerLifetimeScope();

            containerBuilder.RegisterType <ApplicationUserManager>().AsSelf().InstancePerLifetimeScope();
            containerBuilder.RegisterType <ApplicationSignInManager>().AsSelf().InstancePerLifetimeScope();
            containerBuilder.Register <IAuthenticationManager>(c => HttpContext.Current.GetOwinContext().Authentication).InstancePerLifetimeScope();
            containerBuilder.Register <IDataProtectionProvider>(c => app.GetDataProtectionProvider()).InstancePerLifetimeScope();
        }
 public static IAppBuilder AddCustomCmsAspNetIdentity <TUser>(this IAppBuilder app, ApplicationOptions applicationOptions) where TUser : IdentityUser, IUIUser, new()
 {
     applicationOptions.DataProtectionProvider = app.GetDataProtectionProvider();
     app.CreatePerOwinContext <ApplicationOptions>((Func <ApplicationOptions>)(() => applicationOptions));
     app.CreatePerOwinContext <ApplicationDbContext <TUser> >(new Func <IdentityFactoryOptions <ApplicationDbContext <TUser> >, IOwinContext, ApplicationDbContext <TUser> >(ApplicationDbContext <TUser> .Create));
     app.CreatePerOwinContext <ApplicationRoleManager <TUser> >(new Func <IdentityFactoryOptions <ApplicationRoleManager <TUser> >, IOwinContext, ApplicationRoleManager <TUser> >(ApplicationRoleManager <TUser> .Create));
     app.CreatePerOwinContext <ApplicationUserManager <TUser> >(new Func <IdentityFactoryOptions <ApplicationUserManager <TUser> >, IOwinContext, ApplicationUserManager <TUser> >(ApplicationUserManagerInitializer <TUser> .Create));
     app.CreatePerOwinContext <ApplicationSignInManager <TUser> >(new Func <IdentityFactoryOptions <ApplicationSignInManager <TUser> >, IOwinContext, ApplicationSignInManager <TUser> >(ApplicationSignInManager <TUser> .Create));
     app.CreatePerOwinContext <UIUserProvider>(new Func <IdentityFactoryOptions <UIUserProvider>, IOwinContext, UIUserProvider>(ApplicationUserProvider <TUser> .Create));
     app.CreatePerOwinContext <UIRoleProvider>(new Func <IdentityFactoryOptions <UIRoleProvider>, IOwinContext, UIRoleProvider>(ApplicationRoleProvider <TUser> .Create));
     app.CreatePerOwinContext <UIUserManager>(new Func <IdentityFactoryOptions <UIUserManager>, IOwinContext, UIUserManager>(ApplicationUIUserManager <TUser> .Create));
     app.CreatePerOwinContext <UISignInManager>(new Func <IdentityFactoryOptions <UISignInManager>, IOwinContext, UISignInManager>(ApplicationUISignInManager <TUser> .Create));
     ConnectionStringNameResolver.ConnectionStringNameFromOptions = applicationOptions.ConnectionStringName;
     return(app);
 }
Esempio n. 42
0
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();
            app.CreatePerOwinContext(() => new UserManager(new IdentityStore(SessionManager.OpenSession())));
            app.CreatePerOwinContext <SignInManager>((options, context) =>
                                                     new SignInManager(context.GetUserManager <UserManager>(), context.Authentication));
            DataProtectionProvider = app.GetDataProtectionProvider();

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Account/Login"),
                Provider           = new CookieAuthenticationProvider()
            });
        }
Esempio n. 43
0
    public void ConfigureAuth(IAppBuilder app)
    {
        var builder = new ContainerBuilder();

        builder.RegisterControllers(typeof(MvcApplication).Assembly);
        builder.Register(c => new IdentityFactoryOptions <ApplicationUserManager>()
        {
            DataProtectionProvider = app.GetDataProtectionProvider()
        }).SingleInstance();
        //Or
        //builder.Register<IDataProtectionProvider>(c =>app.GetDataProtectionProvider()).SingleInstance();
        var container = builder.Build();

        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
    }
Esempio n. 44
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            ConfigureOAuthTokenGeneration(app);
            ConfigureOAuthTokenConsumption(app);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
            DataProtectionProvider = app.GetDataProtectionProvider();

            var httpConfig = new HttpConfiguration();

            //change this configuration as you want.
            var cors = new EnableCorsAttribute("*", "*", "*");

            httpConfig.EnableCors(cors);
            app.MapSignalR();
        }
Esempio n. 45
0
        private void ConfigAutofac(IAppBuilder app)
        {
            var builder = new ContainerBuilder();

            //builder.RegisterControllers(typeof(MvcApplication).Assembly);
            builder.RegisterControllers(Assembly.GetExecutingAssembly());
            var assembliesGtripWebApi = AppDomain.CurrentDomain.GetAssemblies().Where(x => x.FullName.Contains("NBT.Web.Api"));

            builder.RegisterApiControllers(assembliesGtripWebApi.ToArray());

            builder.RegisterType <UnitOfWork>().As <IUnitOfWork>().InstancePerRequest();
            builder.RegisterType <DbFactory>().As <IDbFactory>().InstancePerRequest();

            builder.RegisterType <MasterDBContext>().AsSelf().InstancePerRequest();

            builder.RegisterType <PermissionProvider>().As <IPermissionProvider>().InstancePerRequest();
            builder.RegisterType <TourTypeProvider>().As <ITourTypeProvider>().InstancePerRequest();
            builder.RegisterType <BlogPostTypeProvider>().As <IBlogPostTypeProvider>().InstancePerRequest();
            builder.RegisterType <SettingsProvider>().As <ISettingsProvider>().InstancePerRequest();

            builder.RegisterType <RoleStore <AppRole> >().As <IRoleStore <AppRole, string> >();
            builder.RegisterType <ApplicationUserStore>().As <IUserStore <AppUser> >().InstancePerRequest();
            builder.RegisterType <ApplicationUserManager>().AsSelf().InstancePerRequest();
            builder.RegisterType <ApplicationSignInManager>().AsSelf().InstancePerRequest();

            builder.RegisterType <ApplicationRoleManager>().AsSelf().InstancePerRequest();

            builder.Register(c => HttpContext.Current.GetOwinContext().Authentication).InstancePerRequest();
            builder.Register(c => app.GetDataProtectionProvider()).InstancePerRequest();

            builder.RegisterGeneric(typeof(RepositoryBase <>)).As(typeof(IRepository <>)).InstancePerRequest();
            builder.RegisterGeneric(typeof(ServiceBase <>)).As(typeof(IService <>)).InstancePerRequest();

            // Repositories
            builder.RegisterAssemblyTypes(typeof(ErrorRepository).Assembly)
            .Where(t => t.Name.EndsWith("Repository"))
            .AsImplementedInterfaces().InstancePerRequest();

            // Services
            builder.RegisterAssemblyTypes(typeof(ErrorService).Assembly)
            .Where(t => t.Name.EndsWith("Service"))
            .AsImplementedInterfaces().InstancePerRequest();

            var container = builder.Build();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
            GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver((IContainer)container); //Set the WebApi DependencyResolver
        }
Esempio n. 46
0
        private static void ConfigureAuth(IAppBuilder appBuilder)
        {
            const int twoWeeks = 14;

            ProjectObjectFactory.Container.Configure(config => config.For <IDataProtectionProvider>()
                                                     .HybridHttpOrThreadLocalScoped()
                                                     .Use(() => appBuilder.GetDataProtectionProvider()));

            appBuilder.CreatePerOwinContext(
                () => ProjectObjectFactory.Container.GetInstance <ApplicationUserManager>());

            appBuilder.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Account/Login"),
                ExpireTimeSpan     = TimeSpan.FromDays(twoWeeks),
                SlidingExpiration  = true,
                CookieName         = "MyWeb",
                Provider           = new CookieAuthenticationProvider
                {
                    OnValidateIdentity =
                        ProjectObjectFactory.Container.GetInstance <IApplicationUserManager>().OnValidateIdentity()
                }
            });

            ProjectObjectFactory.Container.GetInstance <IApplicationRoleManager>().SeedDatabase();

            ProjectObjectFactory.Container.GetInstance <IApplicationUserManager>().SeedDatabase();

            appBuilder.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            //appBuilder.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Enables the application to remember the second login verification factor such as phone or email.
            // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            // This is similar to the RememberMe option when you log in.
            // appBuilder.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);


            //appBuilder.UseFacebookAuthentication(
            //   appId: "fdsfdsfs",
            //   appSecret: "fdfsfs");

            //appBuilder.UseGoogleAuthentication(
            //    clientId: "fdsfsdfs",
            //    clientSecret: "fdsfsf");
        }
Esempio n. 47
0
        private void ConfigAutofac(IAppBuilder app)
        {
            var builder = new ContainerBuilder();

            // Register your Web API controllers.
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); //Register WebApi Controllers

            builder.RegisterType <UnitOfWork>().As <IUnitOfWork>().InstancePerRequest();
            builder.RegisterType <BackupUnitOfWork>().As <IBackupUnitOfWork>().InstancePerRequest();
            builder.RegisterType <DbFactory>().As <IDbFactory>().InstancePerRequest();
            builder.RegisterType <DbFactoryBackup>().As <IDbFactoryBackup>().InstancePerRequest();
            //POS1
            builder.RegisterType <POS1UnitOfWork>().As <IPOS1UnitOfWork>().InstancePerRequest();
            builder.RegisterType <POS1DbFactory>().As <IPOS1DbFactory>().InstancePerRequest();
            //POS2
            builder.RegisterType <POS2UnitOfWork>().As <IPOS2UnitOfWork>().InstancePerRequest();
            builder.RegisterType <POS2DbFactory>().As <IPOS2DbFactory>().InstancePerRequest();

            builder.RegisterType <TeduShopDbContext>().AsSelf().InstancePerRequest();
            builder.RegisterType <BackupDbContext>().AsSelf().InstancePerRequest();
            builder.RegisterType <RoleStore <AppRole> >().As <IRoleStore <AppRole, string> >();
            //Asp.net Identity
            builder.RegisterType <ApplicationUserStore>().As <IUserStore <AppUser> >().InstancePerRequest();
            builder.RegisterType <ApplicationUserManager>().AsSelf().InstancePerRequest();
            builder.RegisterType <ApplicationSignInManager>().AsSelf().InstancePerRequest();

            builder.RegisterType <ApplicationRoleManager>().AsSelf().InstancePerRequest();
            //Register sth

            builder.Register(c => HttpContext.Current.GetOwinContext().Authentication).InstancePerRequest();
            builder.Register(c => app.GetDataProtectionProvider()).InstancePerRequest();

            // Repositories
            builder.RegisterAssemblyTypes(typeof(PostCategoryRepository).Assembly)
            .Where(t => t.Name.EndsWith("Repository"))
            .AsImplementedInterfaces().InstancePerRequest();

            // Services
            builder.RegisterAssemblyTypes(typeof(PostCategoryService).Assembly)
            .Where(t => t.Name.EndsWith("Service"))
            .AsImplementedInterfaces().InstancePerRequest();


            Autofac.IContainer container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver((IContainer)container); //Set the WebApi DependencyResolver
        }
Esempio n. 48
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public static void Configure(IAppBuilder app)
        {
            DataProtectionProvider = app.GetDataProtectionProvider();

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Account/Login"),
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Uncomment the following lines to enable logging in with third party login providers
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //   consumerKey: "dfgdfgdfgd",
            //   consumerSecret: "dfgdfffffffg");

            //app.UseLdapAuthentication(new LdapAuthenticationOptions());

            //app.UseFacebookAuthentication(
            //   appId: "134998043776447",
            //   appSecret: "c8b3b4a0878ebe70f9494f93202e203b"
            //);

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "587369244487-4cd2h297b0gispb44lvvbns8ohlvm2fj.apps.googleusercontent.com",
            //    ClientSecret = "lm7FGNTY0Bz_Y3rh0apf2T6F"
            //});

            //app.UseOrcidAuthentication(new OrcidAuthenticationOptions()
            //{
            //    Endpoints = new OrcidAuthenticationEndpoints
            //    {
            //        ApiEndpoint = "https://pub.sandbox.orcid.org/v1.2/0000-0003-0514-2115/orcid-profile",
            //        TokenEndpoint = "https://sandbox.orcid.org/oauth/token",
            //        AuthorizationEndpoint = h"https://sandbox.orcid.org/oauth/authorize?client_idttps://sandbox.orcid.org/oauth/authorize?client_id="
            //                        + clientId + "&response_type=code&scope="
            //                        + "/read-limited" + "&redirect_uri="
            //                        + "http://localhost:55247/Acces"
            //    },
            //    ClientId = clientId,
            //    ClientSecret = clientSecret
            //});
        }
Esempio n. 49
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            DataProtectionProvider = app.GetDataProtectionProvider();
            // 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/Login")
            });

            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
        }
Esempio n. 50
0
        public void Configuration(IAppBuilder app)
        {
            var builder = AutofacConfiguration.Configure();

            builder.Register <IDataProtectionProvider>(c => app.GetDataProtectionProvider()).InstancePerRequest();
            builder.RegisterControllers(typeof(MvcApplication).Assembly);

            var container = builder.Build();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            app.UseAutofacMiddleware(container);
            app.UseAutofacMvc();

            ConfigureAuth(app);
        }
Esempio n. 51
0
        /// <summary>
        /// Factory method that creates the user manager with <see cref="UserStore"/>.
        /// </summary>
        /// <param name="app">Application builder.</param>
        /// <param name="manager">Manager to be initialized.</param>
        public static T Initialize <T>(IAppBuilder app, T manager) where T : UserManager
        {
            var provider = app.GetDataProtectionProvider();

            if (provider != null)
            {
                manager.UserTokenProvider = new DataProtectorTokenProvider <User, int>(provider.Create("Kentico.Membership"));
            }

            manager.PasswordValidator           = new PasswordValidator();
            manager.UserLockoutEnabledByDefault = false;
            manager.EmailService  = new EmailService();
            manager.UserValidator = new UserValidator <User, int>(manager);

            return(manager);
        }
Esempio n. 52
0
        public static void ConfigureAuth(IAppBuilder app, IContainer container)
        {
            // Configure the db context and user manager to use a single instance per request
            //app.CreatePerOwinContext(XAppDbContext.Create);
            //app.CreatePerOwinContext<XUserManager>(XUserManager.Create);
            //app.CreatePerOwinContext<XRoleManager>(XRoleManager.Create);

            app.UseCors(CorsOptions.AllowAll);

            DataProtectionProvider = app.GetDataProtectionProvider();

            ConfigureOAuthTokenGeneration(app, container);

            //// Api controllers with an [Authorize] attribute will be validated with JWT
            ConfigureOAuthTokenConsumption(app, container);
        }
Esempio n. 53
0
        public void ConfigureAuth(IAppBuilder app)
        {
            var container = UnityConfig.GetConfiguredContainer();

            DataProtectionProvider = app.GetDataProtectionProvider();
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                ExpireTimeSpan     = TimeSpan.FromDays(7),
                SlidingExpiration  = true,
                Provider           = new CookieAuthenticationProvider
                {
                    OnValidateIdentity = container.Resolve <IdentityValidator>().ValidateIdentity
                }
            });
        }
Esempio n. 54
0
        protected virtual void ConfigureShell(IAppBuilder app)
        {
            var properties = new AppProperties(app.Properties);
            var token      = properties.OnAppDisposing;

            if (token != CancellationToken.None)
            {
                app.CreatePerOwinContext(
                    () => new AmbientContext(false));

                var dataProtectionProvider = app.GetDataProtectionProvider();
                var extension = new WebApiContainerExtension(dataProtectionProvider, this.OnShellExtraInitialization);
                Shell.Start(extension);
                token.Register(Shell.Shutdown);
            }
        }
Esempio n. 55
0
        public static void AddHmhServices(this IServiceCollection services, IAppBuilder app)
        {
            //Identity
            services.AddScoped <UserManager <User, int>, UserManager>();
            services.AddScoped <SignInManager <User, int>, SignInManager>();
            services.AddScoped <IAuthenticationManager>(_ => HttpContext.Current.GetOwinContext().Authentication);
            services.AddScoped <IDataProtectionProvider>(_ => app.GetDataProtectionProvider());

            //Security
            //services.AddScoped<FunctionMapStore>();
            //services.AddScoped<EntityMapStore>();

            //OAuth
            //services.AddScoped<OAuthClientStore>();
            //services.AddScoped<IClientRefreshTokenStore, OAuthClientRefreshTokenStore>();
        }
Esempio n. 56
0
        private static void RegisterOwinIdentityServices(this Container container, IAppBuilder app)
        {
            container.RegisterSingleton <IAppBuilder>(app);

            container.RegisterSingleton <IPasswordHasher, PasswordHasher>();
            container.RegisterSingleton <IDataProtector>(() => app.GetDataProtectionProvider().Create(purposes: "Identity Data Protection"));
            container.RegisterSingleton <DataProtectorTokenProvider>();
            container.RegisterSingleton <UserManager>();

            container.Register <IAuthenticationManager <UserView>, AuthenticationManager>(Lifestyle.Scoped);
            container.Register(() => container.IsVerifying
                ? new OwinContext().Authentication
                : HttpContext.Current.GetOwinContext().Authentication, Lifestyle.Scoped);

            container.Register <ExceptionHandlingMiddleware>();
        }
Esempio n. 57
0
        public void Configuration(IAppBuilder app)
        {
            ContainerBuilder builder = new ContainerBuilder();

            // AutoMapper config
            builder.Register(c => AutoMapperConfig.Register()).As <IMapper>().InstancePerLifetimeScope().PropertiesAutowired().PreserveExistingDefaults();

            // DbContext config
            builder.RegisterType <UnitOfWork>().As <IUnitOfWork>().InstancePerRequest();
            builder.RegisterType <AppDbContext>().As <IAppDbContext>().InstancePerRequest();
            builder.RegisterType <AppDbContext>().AsSelf().InstancePerRequest();

            // Identity config
            builder.RegisterType <AppSignInManager>().AsSelf().InstancePerRequest();
            builder.Register <IAuthenticationManager>(c => HttpContext.Current.GetOwinContext().Authentication).InstancePerRequest();
            builder.Register <IDataProtectionProvider>(c => app.GetDataProtectionProvider()).InstancePerRequest();
            builder.RegisterType <AppUserManager>().As <IAppUserManager>().InstancePerRequest();
            builder.RegisterType <AppRoleManager>().AsSelf().InstancePerRequest();
            builder.Register(c => new RoleStore <AppRole>(c.Resolve <AppDbContext>())).As <IRoleStore <AppRole, string> >().InstancePerRequest();
            builder.Register(c => new AppUserStore(c.Resolve <IAppDbContext>())).As <IUserStore <AppUser> >().InstancePerRequest();

            // Types config
            builder.RegisterGeneric(typeof(Repository <>)).As((typeof(IRepository <>))).InstancePerRequest();
            builder.RegisterType <ProductRepository>().As <IProductRepository>().InstancePerRequest();
            builder.RegisterType <CategoryRepository>().As <ICategoryRepository>().InstancePerRequest();
            builder.RegisterType <SubategoryRepository>().As <ISubcategoryRepository>().InstancePerRequest();
            builder.RegisterType <OrderRepository>().As <IOrderRepository>().InstancePerRequest();
            builder.RegisterType <CartRepository>().As <ICartRepository>().InstancePerRequest();
            builder.RegisterType <SettingsRepository>().As <ISettingsRepository>();
            builder.RegisterType <MailingService>().As <IMailingService>().InstancePerRequest();
            builder.RegisterType <DotPayPaymentService>().As <IDotPayPaymentService>().InstancePerRequest();

            // Register controllers
            builder.RegisterControllers(typeof(MvcApplication).Assembly);
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

            IContainer container = builder.Build();

            // Set Dependency Resolver
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
            GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);

            app.UseAutofacMiddleware(container);
            app.UseAutofacMvc();

            ConfigureAuth(app);
        }
Esempio n. 58
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context and user manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext <ApplicationUserManager>((o, c) => {
                o.DataProtectionProvider = app.GetDataProtectionProvider();
                return(ApplicationUserManager.Create(o, c));
            });

            // 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
            //app.UseCookieAuthentication(new CookieAuthenticationOptions());
            //app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Configure the application for OAuth based flow
            PublicClientId = "SFH.IT.Hljodrit.Admin";
            OAuthOptions   = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath         = new PathString("/Token"),
                Provider                  = new ApplicationOAuthProvider(PublicClientId),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(7),
                // In production mode set AllowInsecureHttp = false
                AllowInsecureHttp = true
            };
            // Enable the application to use bearer tokens to authenticate users
            app.UseOAuthBearerTokens(OAuthOptions);


            // Uncomment the following lines to enable logging in with third party login providers
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //    consumerKey: "",
            //    consumerSecret: "");

            //app.UseFacebookAuthentication(
            //    appId: "",
            //    appSecret: "");

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});
        }
Esempio n. 59
0
 public static void ConfigureUserService(this IdentityServerServiceFactory factory, IAppBuilder app)
 {
     factory.UserService = new Registration <IUserService, UserService>()
     {
         Mode = RegistrationMode.InstancePerHttpRequest
     };
     factory.Register(new Registration <ApplicationUserManager>()
     {
         Mode = RegistrationMode.InstancePerHttpRequest
     });
     factory.Register(new Registration <IUserStore <ApplicationUser>, ApplicationUserStore>()
     {
         Mode = RegistrationMode.InstancePerHttpRequest
     });
     factory.Register(new Registration <IwsIdentityContext>()
     {
         Mode = RegistrationMode.InstancePerHttpRequest
     });
     factory.Register(new Registration <IDataProtectionProvider>(f => app.GetDataProtectionProvider())
     {
         Mode = RegistrationMode.InstancePerHttpRequest
     });
     factory.Register(new Registration <ConfigurationService>()
     {
         Mode = RegistrationMode.InstancePerHttpRequest
     });
     factory.Register(new Registration <IwsContext>()
     {
         Mode = RegistrationMode.InstancePerHttpRequest
     });
     factory.Register(new Registration <IUserContext, UserContext>()
     {
         Mode = RegistrationMode.InstancePerHttpRequest
     });
     factory.Register(new Registration <IAuthenticationManager>(resolver => HttpContext.Current.GetOwinContext().Authentication)
     {
         Mode = RegistrationMode.InstancePerHttpRequest
     });
     factory.Register(new Registration <IEventDispatcher, NullEventDispatcher>()
     {
         Mode = RegistrationMode.Singleton
     });
     factory.Register(new Registration <IClaimsRepository, ClaimsRepository>()
     {
         Mode = RegistrationMode.InstancePerHttpRequest
     });
 }
Esempio n. 60
0
        public static void RegisterComponents(IAppBuilder app)
        {
            var container = new UnityContainer();

            container.RegisterType <IMapper, AutoMapperMapper>();
            container.RegisterType <ILeadRepository, LeadRepository>();
            container.RegisterType <IUserRepository, UserRepository>();
            container.RegisterType <ILeadService, LeadService>();
            container.RegisterType <IUserService, UserService>();
            container.RegisterType <IEmailService, EmailService>();
            container.RegisterType <IUserStore <User>, ApplicationUserStore>();
            container.RegisterInstance <IDataProtector>(app.GetDataProtectionProvider().Create("EmailConfirmation"));
            container.RegisterType <IUserTokenProvider <User, string>, DataProtectorTokenProvider <User> >();
            container.RegisterType <DbContext, ApplicationDbContext>();

            DependencyResolver.SetResolver(new UnityDependencyResolver(container));
        }