Beispiel #1
0
        private UserManager <ApplicationUser> InitUserManager(UserManager <ApplicationUser> manager)
        {
            manager.UserValidator = new UserValidator <ApplicationUser>(manager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail             = true
            };

            manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength          = 6,
                RequireNonLetterOrDigit = true,
                RequireDigit            = true,
                RequireLowercase        = true,
                RequireUppercase        = true,
            };
            manager.RegisterTwoFactorProvider("PhoneCode", new PhoneNumberTokenProvider <ApplicationUser>
            {
                MessageFormat = "Your security code is: {0}"
            });
            manager.RegisterTwoFactorProvider("EmailCode", new EmailTokenProvider <ApplicationUser>
            {
                Subject    = "Security Code",
                BodyFormat = "Your security code is: {0}"
            });
            manager.EmailService = new EmailService();
            manager.SmsService   = new SmsService();
            var provider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("FilmOverflow");

            manager.UserTokenProvider = new DataProtectorTokenProvider <ApplicationUser>(provider.Create("EmailConfirmation"));
            return(manager);
        }
Beispiel #2
0
        /// <summary>
        /// The configure user manager.
        /// </summary>
        /// <param name="userStore">
        /// The user store.
        /// </param>
        /// <param name="app">
        /// The app.
        /// </param>
        /// <returns>
        /// The <see cref="UserManager{Person}"/>.
        /// </returns>
        public static UserManager <Person> ConfigureUserManager(UserStore <Person> userStore, IAppBuilder app)
        {
            var userManager = new UserManager <Person>(userStore);

            userManager.UserValidator = new UserValidator <Person>(userManager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail             = true
            };

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

            // Configure user lockout defaults
            userManager.UserLockoutEnabledByDefault          = true;
            userManager.DefaultAccountLockoutTimeSpan        = TimeSpan.FromMinutes(5);
            userManager.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.
            userManager.RegisterTwoFactorProvider(
                "Phone Code",
                new PhoneNumberTokenProvider <Person>
            {
                MessageFormat = "Your security code is {0}"
            });

            userManager.RegisterTwoFactorProvider(
                "Email Code",
                new EmailTokenProvider <Person>
            {
                Subject    = "Security Code",
                BodyFormat = "Your security code is {0}"
            });

            ////this.EmailService = new EmailService();
            ////this.SmsService = new SmsService();

            if (app != null)
            {
                var dataProtectionProvider = app.GetDataProtectionProvider();
                if (dataProtectionProvider != null)
                {
                    userManager.UserTokenProvider =
                        new DataProtectorTokenProvider <Person>(dataProtectionProvider.Create("ASP.NET Identity"));
                }
            }

            return(userManager);
        }
Beispiel #3
0
        /// <summary>
        /// Configure user manager.
        /// </summary>
        /// <typeparam name="TUser">Type of the user.</typeparam>
        /// <param name="manager">User manager which has to be configured.</param>
        /// <param name="emailDisplayName">Display name for the email service.</param>
        public static void ConfigureUserManager <TUser>(this UserManager <TUser> manager, string emailDisplayName)
            where TUser : DubUser
        {
            if (manager == null)
            {
                throw new ArgumentNullException("manager");
            }

            if (string.IsNullOrWhiteSpace(emailDisplayName))
            {
                throw new ArgumentException("Email display name could not be empty.", "emailDisplayName");
            }

            manager.UserValidator = new UserValidator <TUser>(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.
            var phoneProvider = new PhoneNumberTokenProvider <TUser>
            {
                MessageFormat = "Your security code is {0}"
            };
            var emailProvider = new EmailTokenProvider <TUser>
            {
                Subject    = "Security Code",
                BodyFormat = "Your security code is {0}"
            };

            manager.RegisterTwoFactorProvider("Phone Code", phoneProvider);
            manager.RegisterTwoFactorProvider("Email Code", emailProvider);
            manager.EmailService = new MarkdownEmailService(emailDisplayName);
            manager.SmsService   = new EmptySmsService();
        }
        public static UserManager <ApplicationIdentityUser, Int32> CreateUserManager(DbContext context)
        {
            var manager = new UserManager <ApplicationIdentityUser, Int32>(new UserStore <ApplicationIdentityUser, ApplicationIdentityRole, Int32, ApplicationIdentityUserLogin, ApplicationIdentityUserRole, ApplicationIdentityUserClaim>(context));

            // Configure validation logic for usernames
            manager.UserValidator = new UserValidator <ApplicationIdentityUser, Int32>(manager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail             = false
            };

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

            // 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 in here.
            manager.RegisterTwoFactorProvider("PhoneCode", new PhoneNumberTokenProvider <ApplicationIdentityUser, Int32>
            {
                MessageFormat = "Your security code is: {0}"
            });

            manager.RegisterTwoFactorProvider("EmailCode", new EmailTokenProvider <ApplicationIdentityUser, Int32>
            {
                Subject    = "SecurityCode",
                BodyFormat = "Your security code is {0}"
            });

            manager.EmailService = new EmailService();
            manager.SmsService   = new SmsService();

            var provider = new DpapiDataProtectionProvider("Wizitup");

            manager.UserTokenProvider = new DataProtectorTokenProvider <ApplicationIdentityUser, Int32>(
                provider.Create("ASP.NET Identity"));

            return(manager);
        }
Beispiel #5
0
        public IdentityServices(DbContext context, IAuthenticationManager authenticationMana, UserStore<IdentityUser> userStor, UserManager<IdentityUser> userMena)
        {
            db = context;
            userStore = userStor;
            userMenager = userMena;
            authenticationManager = authenticationMana;

            userMenager.UserValidator = new UserValidator<IdentityUser>(userMenager) { RequireUniqueEmail = true, AllowOnlyAlphanumericUserNames = false };
            userMenager.PasswordValidator = new PasswordValidator() { RequiredLength = 6, RequireLowercase = true, RequireUppercase = true, RequireDigit = true };

            signInMenager = new SignInManager<IdentityUser, string>(userMenager, authenticationManager);
            
            userMenager.RegisterTwoFactorProvider("EmailCode", new EmailTokenProvider<IdentityUser>
            {
                Subject = "Security Code",
                BodyFormat = "Your security code is {0}"
            });

            userMenager.EmailService = new EmailService();

            var dataProtectionProvider = Startup.dataProtectionProvider;

            if (dataProtectionProvider != null)
            {
                IDataProtector dataProtector = dataProtectionProvider.Create("ASP.NET Identity");
                userMenager.UserTokenProvider = new DataProtectorTokenProvider<IdentityUser>(dataProtector);
            }
        }
Beispiel #6
0
        public void Configuration(IAppBuilder app)
        {
            const string connectionString =
                @"Data Source=(LocalDb)\MSSQLLocalDB;Database=Pluralsight.AspNetIdentityDemo.Module3.2;trusted_connection=yes;";

            app.CreatePerOwinContext(() => new IdentityDbContext(connectionString));
            app.CreatePerOwinContext <UserStore <IdentityUser> >((opt, cont) => new UserStore <IdentityUser>(cont.Get <IdentityDbContext>()));
            app.CreatePerOwinContext <UserManager <IdentityUser> >(
                (opt, cont) =>
            {
                var usermanager = new UserManager <IdentityUser>(cont.Get <UserStore <IdentityUser> >());
                usermanager.RegisterTwoFactorProvider("SMS", new PhoneNumberTokenProvider <IdentityUser> {
                    MessageFormat = "Token: {0}"
                });
                usermanager.SmsService = new SmsService();
                return(usermanager);
            });
            app.CreatePerOwinContext <SignInManager <IdentityUser, string> >(
                (opt, cont) => new SignInManager <IdentityUser, string>(cont.Get <UserManager <IdentityUser> >(), cont.Authentication));

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie
            });

            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
        }
Beispiel #7
0
        public AuthRepository(ILogger logger)
        {
            this.logger = logger;

            dbContext   = new AuthDbContext();
            userManager = new UserManager <AppUser>(new UserStore <AppUser>(dbContext));

            userManager.RegisterTwoFactorProvider(GoogleAuthenticatorName, new GoogleAuthenticatorTokenProvider());
            userManager.UserTokenProvider = new EmailTokenProvider <AppUser>();
        }
Beispiel #8
0
        public static UserManager <ApplicationIdentityUser, int> CreateUserManager(
            IEmailService emailService,
            ISmsService smsService,
            IUserStore <ApplicationIdentityUser, int> userStore)
        {
            var manager = new UserManager <ApplicationIdentityUser, int>(
                userStore
                );

            manager.UserValidator = new  UserValidator <ApplicationIdentityUser, int>(manager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail             = true
            };

            manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength          = 6,
                RequireNonLetterOrDigit = true,
                RequireDigit            = true,
                RequireLowercase        = true,
                RequireUppercase        = true,
            };

            manager.UserLockoutEnabledByDefault          = true;
            manager.DefaultAccountLockoutTimeSpan        = TimeSpan.FromMinutes(5);
            manager.MaxFailedAccessAttemptsBeforeLockout = 5;

            manager.RegisterTwoFactorProvider("PhoneCode", new PhoneNumberTokenProvider <ApplicationIdentityUser, int>
            {
                MessageFormat = "Your security code is: {0}"
            });
            manager.RegisterTwoFactorProvider("EmailCode", new EmailTokenProvider <ApplicationIdentityUser, int>
            {
                Subject    = "SecurityCode",
                BodyFormat = "Your security code is {0}"
            });

            manager.EmailService = emailService;
            manager.SmsService   = smsService;

            return(manager);
        }
Beispiel #9
0
        private static void ConfigureContainer()
        {
            var container = new Container();

            container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();

            const string connectionString = @"Data Source=(LocalDb)\MSSQLLocalDB;Database=Pluralsight.AspNetIdentityDemo.Module2.2;trusted_connection=true";

            container.Register(() => new IdentityDbContext(connectionString), Lifestyle.Scoped);
            container.Register(() => new UserStore <IdentityUser>(container.GetInstance <IdentityDbContext>()), Lifestyle.Scoped);
            container.Register(() =>
            {
                var usermanager = new UserManager <IdentityUser, string>(container.GetInstance <UserStore <IdentityUser> >());

                usermanager.RegisterTwoFactorProvider("SMS", new PhoneNumberTokenProvider <IdentityUser> {
                    MessageFormat = "Token: {0}"
                });
                usermanager.SmsService = new SmsService();

                //usermanager.UserTokenProvider = new DataProtectorTokenProvider<IdentityUser>(opt.DataProtectionProvider.Create());
                usermanager.EmailService = new EmailService();

                usermanager.UserValidator = new UserValidator <IdentityUser, string>(usermanager)
                {
                    RequireUniqueEmail = true
                };
                usermanager.PasswordValidator = new PasswordValidator
                {
                    RequireDigit            = true,
                    RequireLowercase        = true,
                    RequireNonLetterOrDigit = true,
                    RequireUppercase        = true,
                    RequiredLength          = 8
                };

                usermanager.UserLockoutEnabledByDefault          = true;
                usermanager.MaxFailedAccessAttemptsBeforeLockout = 2;
                usermanager.DefaultAccountLockoutTimeSpan        = TimeSpan.FromMinutes(3);

                return(usermanager);
            }, Lifestyle.Scoped);

            container.Register <SignInManager <IdentityUser, string> >(Lifestyle.Scoped);

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

            container.RegisterMvcControllers(Assembly.GetExecutingAssembly());

            container.Verify();

            DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
        }
 public static UserManager<ApplicationIdentityUser, int> CreateUserManager(DbContext context)
 {
     var manager = new UserManager<ApplicationIdentityUser, int>(new UserStore<ApplicationIdentityUser, ApplicationIdentityRole, int, ApplicationIdentityUserLogin, ApplicationIdentityUserRole, ApplicationIdentityUserClaim>(context));
     // Configure validation logic for usernames
     manager.UserValidator = new  UserValidator<ApplicationIdentityUser, int>(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 in here.
     manager.RegisterTwoFactorProvider("PhoneCode", new PhoneNumberTokenProvider<ApplicationIdentityUser, int>
     {
         MessageFormat = "Your security code is: {0}"
     });
     manager.RegisterTwoFactorProvider("EmailCode", new EmailTokenProvider<ApplicationIdentityUser, int>
     {
         Subject = "SecurityCode",
         BodyFormat = "Your security code is {0}"
     });
     manager.EmailService = new EmailService();
     manager.SmsService = new SmsService();
     return manager;
 }
Beispiel #11
0
        public async Task TestSendCodeView()
        {
            UserManager.RegisterTwoFactorProvider("prov", new DataProtectorTokenProvider <ApplicationUser, string>(new TestDataProtection()));
            var signInManager = new ApplicationSignInManager(UserManager, GetAuthenticationManager(true));
            var controller    = new AccountController(UserManager, signInManager);

            SetupControllerForTests(controller);

            var result = await controller.SendCode("", false);

            Assert.IsInstanceOfType(result, typeof(ViewResult));
            var viewResult = (ViewResult)result;

            Assert.AreEqual(string.Empty, viewResult.ViewName);
        }
        public AccountController(UserManager <ApplicationUser> _userManager, IWorkflowMessageService workflowMessageServ, IIdentityMessageService emailService)
        {
            userManager            = _userManager;
            workflowMessageService = workflowMessageServ;

            userManager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider <ApplicationUser>
            {
                Subject    = "Security Code",
                BodyFormat = "Your security code is {0}"
            });

            var provider = new DpapiDataProtectionProvider("SampleAppName");

            userManager.UserTokenProvider = new DataProtectorTokenProvider <ApplicationUser>(provider.Create("SampleTokenName"));
            userManager.EmailService      = emailService;
        }
        public static void ConfigureContainer()
        {
            var container = new Container();

            container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();
            const string connectionString = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=DBPluralsightExtendedUser;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";

            container.Register(() => new ExtendedUserDbContext(connectionString), Lifestyle.Scoped);                                    //Passing connection sring to Entity framework
            container.Register(() => new UserStore <ExtendingUser>(container.GetInstance <ExtendedUserDbContext>()), Lifestyle.Scoped); // registring User Store with DI Container
            //REgistring User Manger in DI Container
            container.Register(() =>
            {
                var usermanager = new UserManager <ExtendingUser, string>(container.GetInstance <UserStore <ExtendingUser> >());
                usermanager.RegisterTwoFactorProvider("SMS", new PhoneNumberTokenProvider <ExtendingUser, string> {
                    MessageFormat = "Your security code is: {0}"
                });                                                                                                                                                  // here registring the phone number provider for reciving the code.
                usermanager.SmsService = new SmsService();

                usermanager.EmailService  = new EmailService();
                usermanager.UserValidator = new UserValidator <ExtendingUser>(usermanager)
                {
                    RequireUniqueEmail = true, AllowOnlyAlphanumericUserNames = true
                };                                                    // This code will validate the unique number of users in system
                usermanager.PasswordValidator = new PasswordValidator // this code will generate policy for password .
                {
                    RequireDigit            = true,
                    RequiredLength          = 8,
                    RequireLowercase        = true,
                    RequireUppercase        = true,
                    RequireNonLetterOrDigit = true
                };
                usermanager.UserLockoutEnabledByDefault          = true;                     // This will enable 1 in database for LockOutEnable field.
                usermanager.MaxFailedAccessAttemptsBeforeLockout = 5;                        // This line of code provide 2  attempts and update end date in LockOutEndDateUtc
                usermanager.DefaultAccountLockoutTimeSpan        = TimeSpan.FromMinutes(15); // User account will be active after 15 mins.
                return(usermanager);
            }, Lifestyle.Scoped);
            // Registering Signin manger with DI Container
            container.Register <SignInManager <ExtendingUser, string> >(Lifestyle.Scoped);
            container.Register(() => container.IsVerifying ? new OwinContext().Authentication :HttpContext.Current.GetOwinContext().Authentication, Lifestyle.Scoped);
            container.RegisterMvcControllers(Assembly.GetExecutingAssembly());
            container.Verify();
            DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
        }
Beispiel #14
0
        public async Task TestExternalLoginCallbackRequiresVerification()
        {
            var user = await UserManager.FindByEmailAsync(TestConfig.TestUserEmail);

            var loginInfo = new UserLoginInfo("TestIssuer", user.Id);
            await UserManager.AddLoginAsync(user.Id, loginInfo);

            await UserStore.SetTwoFactorEnabledAsync(user, true);

            UserManager.RegisterTwoFactorProvider("prov", new DataProtectorTokenProvider <ApplicationUser, string>(new TestDataProtection()));
            var signInManager = new ApplicationSignInManager(UserManager, GetAuthenticationManager(false, true));
            var controller    = new AccountController(UserManager, signInManager);

            SetupControllerForTests(controller);

            var result = await controller.ExternalLoginCallback("/Test");

            Assert.IsInstanceOfType(result, typeof(RedirectToRouteResult));
            var redirectResult = (RedirectToRouteResult)result;

            Assert.AreEqual("SendCode", redirectResult.RouteValues["action"]);
        }
Beispiel #15
0
        public void Configuration(IAppBuilder builder)
        {
            builder.CreatePerOwinContext <DbContext>(() =>
                                                     new IdentityDbContext <UsuarioAplicacao>("DefaultConnection"));

            builder.CreatePerOwinContext <IUserStore <UsuarioAplicacao> >(
                (opcoes, contextoOwin) =>
            {
                var dbContext = contextoOwin.Get <DbContext>();
                return(new UserStore <UsuarioAplicacao>(dbContext));
            });

            builder.CreatePerOwinContext <RoleStore <IdentityRole> >(
                (opcoes, contextoOwin) =>
            {
                var dbContext = contextoOwin.Get <DbContext>();
                return(new RoleStore <IdentityRole>(dbContext));
            });

            builder.CreatePerOwinContext <RoleManager <IdentityRole> >(
                (opcoes, contextoOwin) =>
            {
                var roleStore = contextoOwin.Get <RoleStore <IdentityRole> >();
                return(new RoleManager <IdentityRole>(roleStore));
            });

            builder.CreatePerOwinContext <UserManager <UsuarioAplicacao> >(
                (opcoes, contextoOwin) =>
            {
                var userStore   = contextoOwin.Get <IUserStore <UsuarioAplicacao> >();
                var userManager = new UserManager <UsuarioAplicacao>(userStore);

                var userValidator = new UserValidator <UsuarioAplicacao>(userManager);
                userValidator.RequireUniqueEmail = true;

                userManager.UserValidator     = userValidator;
                userManager.PasswordValidator = new SenhaValidador()
                {
                    TamanhoRequerido = 6,
                    ObrigatorioCaracteresEspeciais = true,
                    ObrigatorioDigitos             = true,
                    ObrigatorioLowerCase           = true,
                    ObrigatorioUpperCase           = true
                };

                userManager.EmailService = new EmailServico();
                userManager.SmsService   = new SmsServico();

                userManager.RegisterTwoFactorProvider(
                    "SMS",
                    new PhoneNumberTokenProvider <UsuarioAplicacao>
                {
                    MessageFormat = "Codigo de autenticacao: {0}"
                });

                var dataProtectionProvider        = opcoes.DataProtectionProvider;
                var dataProtectionProviderCreated = dataProtectionProvider.Create("OrisCenter.Key");

                userManager.UserTokenProvider = new DataProtectorTokenProvider <UsuarioAplicacao>(dataProtectionProviderCreated);

                userManager.MaxFailedAccessAttemptsBeforeLockout = 3;
                userManager.DefaultAccountLockoutTimeSpan        = TimeSpan.FromMinutes(5);
                userManager.UserLockoutEnabledByDefault          = true;

                return(userManager);
            });

            builder.CreatePerOwinContext <SignInManager <UsuarioAplicacao, string> >(
                (opcoes, contextoOwin) =>
            {
                var userManager   = contextoOwin.Get <UserManager <UsuarioAplicacao> >();
                var signInManager =
                    new SignInManager <UsuarioAplicacao, string>(
                        userManager,
                        contextoOwin.Authentication);

                return(signInManager);
            });

            builder.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                Provider           = new CookieAuthenticationProvider
                {
                    OnValidateIdentity =
                        SecurityStampValidator.OnValidateIdentity <UserManager <UsuarioAplicacao>, UsuarioAplicacao>(
                            TimeSpan.FromSeconds(0),
                            (manager, usuario) => manager.CreateIdentityAsync(usuario, DefaultAuthenticationTypes.ApplicationCookie))
                }
            });

            builder.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            builder.UseTwoFactorSignInCookie(
                DefaultAuthenticationTypes.TwoFactorCookie,
                TimeSpan.FromMinutes(5)
                );

            builder.UseTwoFactorRememberBrowserCookie(
                DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            builder.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions
            {
                ClientId     = ConfigurationManager.AppSettings["google:client_id"],
                ClientSecret = ConfigurationManager.AppSettings["google:client_secret"],
                Caption      = "Google"
            });

            using (var dbContext = new IdentityDbContext <UsuarioAplicacao>("DefaultConnection"))
            {
                CriarRoles(dbContext);
                CriarAdministrador(dbContext);
            }
        }
        public void Configuration(IAppBuilder app)
        {
            //This logic is not neccesary becuase it is resolved with simple injector dependency resolver
            //*********************************************************************************************************************************
            const string connectionString =
                @"Data Source=.\sqlexpress;Initial Catalog=AspIdentityDbWeb;Integrated Security=True";

            app.CreatePerOwinContext(() => new IdentityDbContext(connectionString));
            app.CreatePerOwinContext <UserStore <IdentityUser> >((opt, cont) =>
                                                                 new UserStore <IdentityUser>(cont.Get <IdentityDbContext>()));
            app.CreatePerOwinContext <UserManager <IdentityUser> >(
                (opt, cont) =>
            {
                var userManager = new UserManager <IdentityUser>(cont.Get <UserStore <IdentityUser> >());
                userManager.RegisterTwoFactorProvider("SMS", new PhoneNumberTokenProvider <IdentityUser> {
                    MessageFormat = "Token: {0}"
                });
                userManager.SmsService        = new SmsService();
                userManager.UserTokenProvider = new DataProtectorTokenProvider <IdentityUser, string>(opt.DataProtectionProvider.Create());
                userManager.EmailService      = new EmailService();

                userManager.UserValidator = new UserValidator <IdentityUser>(userManager)
                {
                    RequireUniqueEmail = true
                };
                userManager.PasswordValidator = new PasswordValidator
                {
                    RequireDigit            = true,
                    RequireLowercase        = true,
                    RequireNonLetterOrDigit = true,
                    RequireUppercase        = true,
                    RequiredLength          = 8
                };

                userManager.UserLockoutEnabledByDefault          = true;
                userManager.MaxFailedAccessAttemptsBeforeLockout = 2;
                userManager.DefaultAccountLockoutTimeSpan        = TimeSpan.FromMinutes(3);

                return(userManager);
            });

            app.CreatePerOwinContext <SignInManager <IdentityUser, string> >(
                (opt, cont) => new SignInManager <IdentityUser, string>(cont.Get <UserManager <IdentityUser> >(), cont.Authentication));
            //*********************************************************************************************************************************

            //For extended user, defaults are changed
            //************************************************************************************************************************
            //app.CreatePerOwinContext(() => new ExtendendUserDbContext(connectionString));
            //app.CreatePerOwinContext<UserStore<ExtendedUser>>((opt, cont) =>
            //    new UserStore<ExtendedUser>(cont.Get<ExtendendUserDbContext>()));
            //app.CreatePerOwinContext<UserManager<ExtendedUser>>(
            //    (opt, cont) => new UserManager<ExtendedUser>(cont.Get<UserStore<ExtendedUser>>()));
            //app.CreatePerOwinContext<SignInManager<ExtendedUser, string>>(
            //    (opt, cont) => new SignInManager<ExtendedUser, string>(cont.Get<UserManager<ExtendedUser>>(), cont.Authentication));
            //************************************************************************************************************************

            //To use simple dependency resolver uncomment this method
            //*********************************************************************************************************************************
            //app.CreatePerOwinContext<UserManager<IdentityUser, string>>(() => DependencyResolver.Current
            //    .GetService<UserManager<IdentityUser, string>>());
            //*********************************************************************************************************************************

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                Provider           = new CookieAuthenticationProvider
                {
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <UserManager <IdentityUser, string>, IdentityUser>(
                        validateInterval: TimeSpan.FromSeconds(3),
                        regenerateIdentity: (manager, user) => manager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie))
                }
            });

            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
            app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions
            {
                ClientId     = ConfigurationManager.AppSettings["google:ClientId"],
                ClientSecret = ConfigurationManager.AppSettings["google:ClientSecret"],
                Caption      = "Google"
            });
        }
Beispiel #17
0
        public void Configuration(IAppBuilder app)
        {
            const string connectionString =
                @"Data Source=(LocalDb)\MSSQLLocalDB;Database=Pluralsight.AspNetIdentityDemo.Module3.3;trusted_connection=yes;";

            app.CreatePerOwinContext(() => new IdentityDbContext(connectionString));
            app.CreatePerOwinContext <UserStore <IdentityUser> >((opt, cont) => new UserStore <IdentityUser>(cont.Get <IdentityDbContext>()));
            app.CreatePerOwinContext <UserManager <IdentityUser> >(
                (opt, cont) =>
            {
                var usermanager = new UserManager <IdentityUser>(cont.Get <UserStore <IdentityUser> >());
                usermanager.RegisterTwoFactorProvider("SMS", new PhoneNumberTokenProvider <IdentityUser> {
                    MessageFormat = "Token: {0}"
                });
                usermanager.SmsService        = new SmsService();
                usermanager.UserTokenProvider = new DataProtectorTokenProvider <IdentityUser>(opt.DataProtectionProvider.Create());
                usermanager.EmailService      = new EmailService();

                usermanager.UserValidator = new UserValidator <IdentityUser>(usermanager)
                {
                    RequireUniqueEmail = true
                };
                usermanager.PasswordValidator = new PasswordValidator
                {
                    RequireDigit            = true,
                    RequireLowercase        = true,
                    RequireNonLetterOrDigit = true,
                    RequireUppercase        = true,
                    RequiredLength          = 8
                };

                usermanager.UserLockoutEnabledByDefault          = true;
                usermanager.MaxFailedAccessAttemptsBeforeLockout = 2;
                usermanager.DefaultAccountLockoutTimeSpan        = TimeSpan.FromMinutes(3);

                return(usermanager);
            });
            app.CreatePerOwinContext <SignInManager <IdentityUser, string> >(
                (opt, cont) => new SignInManager <IdentityUser, string>(cont.Get <UserManager <IdentityUser> >(), cont.Authentication));

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                Provider           = new CookieAuthenticationProvider
                {
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <UserManager <IdentityUser>, IdentityUser>(
                        validateInterval: TimeSpan.FromSeconds(3),
                        regenerateIdentity: (manager, user) => manager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie))
                }
            });

            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions
            {
                ClientId     = ConfigurationManager.AppSettings["google:ClientId"],
                ClientSecret = ConfigurationManager.AppSettings["google:ClientSecret"],
                Caption      = "Google"
            });
        }