Ejemplo n.º 1
0
 public UsuariosService(IIdentityRepository identity, IMapper mapper, IIdentityValidator <Usuario> validator, IPasswordHasher hasher)
 {
     this.myIdentity       = identity;
     this.myMapper         = mapper;
     this.myValidator      = validator;
     this.myPasswordHasher = hasher;
 }
Ejemplo n.º 2
0
        public UserAuthenticationOptions()
        {
            AccessTokenExpireTimeSpan  = TimeSpan.FromMinutes(30);
            RefreshTokenExpireTimeSpan = TimeSpan.FromMinutes(60);
            TokenEndpointPath          = new PathString("/token");

            PasswordValidator = new Microsoft.AspNet.Identity.PasswordValidator();
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Setup OAuth2 Server
        /// </summary>
        /// <param name="app"></param>
        /// <param name="identityValidator">Identity Validator</param>
        public void ConfigureAuth(IAppBuilder app, IIdentityValidator identityValidator)
        {
            _identityValidator = identityValidator;

            // Enable the External Sign In Cookie.
            app.SetDefaultSignInAsAuthenticationType("Application");
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "Application",
                AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Passive,
                CookieName         = $"{CookieAuthenticationDefaults.CookiePrefix}Application",
                ExpireTimeSpan     = TimeSpan.FromMinutes(5),
                LoginPath          = new PathString(Paths.Login),
                LogoutPath         = new PathString(Paths.Logout),
            });
            app.SetDefaultSignInAsAuthenticationType("Application");

            // Setup OAuth2 Authorization Server
            app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
            {
                AuthorizeEndpointPath       = new PathString(Paths.Authorize),
                TokenEndpointPath           = new PathString(Paths.Token),
                ApplicationCanDisplayErrors = true,
                AllowInsecureHttp           = true,

                #region Token generation settings
                AccessTokenExpireTimeSpan = JwtTokenParameters.TokenExpireTime,

                //The JwtFormat class in Microsoft.Owin.Security.Jwt is not work here. It does not impletement public string Protect(AuthenticationTicket data).
                //It can not convert AuthenticationTicket into Jwt.
                AccessTokenFormat = new JwtFormat(JwtTokenParameters.Issuer, JwtTokenParameters.Audience, JwtTokenParameters.SecurityKey),
                #endregion

                // Authorization server provider which controls the lifecycle of Authorization Server
                Provider = new OAuthAuthorizationServerProvider
                {
                    OnValidateClientRedirectUri     = ValidateClientRedirectUri,
                    OnValidateClientAuthentication  = ValidateClientAuthentication,
                    OnGrantResourceOwnerCredentials = GrantResourceOwnerCredentials,
                    OnGrantClientCredentials        = GrantClientCredetails
                },

                // Authorization code provider which creates and receives the authorization code.
                AuthorizationCodeProvider = new AuthenticationTokenProvider
                {
                    OnCreate  = CreateAuthenticationCode,
                    OnReceive = ReceiveAuthenticationCode,
                },

                // Refresh token provider which creates and receives refresh token.
                RefreshTokenProvider = new AuthenticationTokenProvider
                {
                    OnCreate  = CreateRefreshToken,
                    OnReceive = ReceiveRefreshToken,
                }
            });
        }
Ejemplo n.º 4
0
        public static CarsSaleUserManager Create(
            IdentityFactoryOptions <CarsSaleUserManager> options,
            IOwinContext context,
            IIdentityValidator <string> passwordValidator)
        {
            var manager = Create(context);

            manager.PasswordValidator = passwordValidator;
            return(manager);
        }
Ejemplo n.º 5
0
        public UserAuthenticationOptions(ICoreUserContext userContext, PathString tokenEndpointPath, TimeSpan accessTokenExpireTimeSpan, TimeSpan refreshTokenExpireTimeSpan, bool allowInsecureHttp = true)
        {
            UserContext                = userContext;
            TokenEndpointPath          = tokenEndpointPath;
            AccessTokenExpireTimeSpan  = accessTokenExpireTimeSpan;
            RefreshTokenExpireTimeSpan = refreshTokenExpireTimeSpan;
            AllowInsecureHttp          = allowInsecureHttp;

            PasswordValidator = new Microsoft.AspNet.Identity.PasswordValidator();
        }
Ejemplo n.º 6
0
 public ApplicationUserManager(
     IUserStore <ApplicationUser> store,
     IUserTokenProvider <ApplicationUser, string> tokenProvider,
     IIdentityValidator <string> passwordValidator,
     Func <UserManager <ApplicationUser>, IIdentityValidator <ApplicationUser> > userValidatorFactory)
     : base(store)
 {
     base.UserTokenProvider = tokenProvider;
     base.PasswordValidator = passwordValidator;
     base.UserValidator     = userValidatorFactory(this);
 }
Ejemplo n.º 7
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TestCaseUserManager" /> class.
 /// </summary>
 /// <param name="store">The IUserStore is responsible for commiting changes via the UpdateAsync/CreateAsync methods</param>
 /// <param name="userValidatorFactory">The user validator factory.</param>
 /// <param name="passwordValidator">The password validator.</param>
 /// <param name="passwordHasher">The password hasher.</param>
 public TestCaseUserManager(
     IUserStore <UserEntity, Guid> store,
     IIdentityUserValidatorFactory userValidatorFactory,
     IIdentityValidator <string> passwordValidator,
     IPasswordHasher passwordHasher)
     : base(store)
 {
     this.UserValidator     = userValidatorFactory.Create(this);
     this.PasswordValidator = passwordValidator;
     this.PasswordHasher    = passwordHasher;
 }
Ejemplo n.º 8
0
        public SignUpOperation(UserManager <User> userManager, IIdentityValidator <User> signUpUserValidator)
        {
            if (userManager == null)
            {
                throw new ArgumentNullException(nameof(userManager));
            }

            if (signUpUserValidator == null)
            {
                throw new ArgumentNullException(nameof(signUpUserValidator));
            }

            this.userManager = userManager;
            this.userManager.UserValidator = signUpUserValidator;
        }
 public UserIdentityApplicationService(
     IClaimsIdentityFactory claimsIdentityFactory,
     IPasswordHasher passwordHasher,
     IIdentityValidator<string> passwordIdentityValidator,
     IIdentityValidator<User> userIdentityValidator,
     IUserRepository userRepository,
     IDbContextScopeFactory dbContextScopeFactory,
     IUserTokenProvider userTokenProvider,
     IUserTokenTwoFactorProvider userTokenTwoFactorProvider,
     IMapper mapper,
     ILog logger)
     : base(dbContextScopeFactory, mapper, logger)
 {
     this.claimsIdentityFactory = claimsIdentityFactory;
     this.passwordHasher = passwordHasher;
     this.passwordIdentityValidator = passwordIdentityValidator;
     this.userIdentityValidator = userIdentityValidator;
     this.userRepository = userRepository;
     this.userTokenProvider = userTokenProvider;
     this.userTokenTwoFactorProvider = userTokenTwoFactorProvider;
 }
Ejemplo n.º 10
0
        public ApplicationUserManager(IUserStore <ApplicationUser, int> store, IDataProtectionProvider dataProtectionProvider,
                                      EmailService emailService, SmsService smsService, IIdentityValidator <string> localizePasswordValidator, IPasswordHasher passwordHasher)
            : base(store)
        {
            //UserValidator = new LocalizeUserValidator<ApplicationUser, int>(this)
            //{
            //    AllowOnlyAlphanumericUserNames = false,
            //    RequireUniqueEmail = true
            //};

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


            // Configure user lockout defaults
            UserLockoutEnabledByDefault = false;
            //DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
            //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.

            //RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser,int>
            //{
            //    MessageFormat = "Your security code is {0}"
            //});

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

            EmailService   = emailService;
            SmsService     = smsService;
            PasswordHasher = passwordHasher;

            UserTokenProvider = new DataProtectorTokenProvider <ApplicationUser, int>(dataProtectionProvider.Create("Khodkar"));
        }
Ejemplo n.º 11
0
 public AccountController(IIdentityValidator identityValidator)
 {
     _identityValidator = identityValidator;
 }
Ejemplo n.º 12
0
        private Container ConfigureIoCContainer(IAppBuilder appBuilder)
        {
            var container = new Container();

            container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();

            appBuilder.Use(
                async(context, next) =>
            {
                using (container.BeginExecutionContextScope())
                {
                    await next();
                }
            });

            container.Register <ILog>(() => LogManager.GetLogger(typeof(LogManager)));

            container.RegisterCollection <Profile>();
            container.Register <IMapper>(() =>
            {
                Mapper.Initialize(configuration =>
                {
                    var profiles = container.GetAllInstances <Profile>();

                    foreach (var profile in profiles)
                    {
                        configuration.AddProfile(profile);
                    }
                });

                return(Mapper.Instance);
            }, Lifestyle.Singleton);

            container.Register <IAmbientDbContextLocator, AmbientDbContextLocator>(Lifestyle.Scoped);
            container.Register <IDbContextScopeFactory>(() => new DbContextScopeFactory());
            container.Register <IUserRepository, UserRepository <ApplicationDbContext> >(Lifestyle.Scoped);

            container.Register <IClaimsIdentityFactory, ClaimsIdentityFactory>(Lifestyle.Scoped);
            container.Register <IPasswordHasher, CryptoPasswordHasher>(Lifestyle.Scoped);
            container.Register <IIdentityValidator <string> >(
                () =>
            {
                var passwordValidator = new PasswordValidator
                {
                    RequiredLength          = 6,
                    RequireNonLetterOrDigit = true,
                    RequireDigit            = true,
                    RequireLowercase        = true,
                    RequireUppercase        = true,
                };

                return(passwordValidator);
            });
            container.Register <IIdentityValidator <User> >(
                () =>
            {
                var userRepository = container.GetInstance <IUserRepository>();
                var userValidator  = new UserValidator(userRepository)
                {
                    AllowOnlyAlphanumericUserNames = false,
                    RequireUniqueEmail             = true
                };

                return(userValidator);
            });
            container.Register <IUserTokenProvider>(
                () =>
            {
                var dataProtectionProvider     = appBuilder.GetDataProtectionProvider();
                var dataProtector              = dataProtectionProvider.Create("ASP.NET Identity");
                var dataProtectorTokenProvider = new DataProtectorTokenProvider(dataProtector);

                return(dataProtectorTokenProvider);
            });

            container.Register <IAuthenticationService, Rfc6238AuthenticationService>(Lifestyle.Scoped);
            container.Register <IAuthenticationManager>(
                () =>
            {
                if (HttpContext.Current != null && HttpContext.Current.Items["owin.Environment"] == null &&
                    container.IsVerifying)
                {
                    return(new OwinContext().Authentication);
                }

                return(HttpContext.Current.GetOwinContext().Authentication);
            });
            container.Register <IIdentityProvider, IdentityProvider>(Lifestyle.Scoped);
            container.Register <IIdentityMessageService, SmsService>(Lifestyle.Scoped);
            container.Register <IUserTokenTwoFactorProvider, UserTokenTwoFactorProvider>(Lifestyle.Scoped);

            container.Register <IUserIdentityApplicationService>(
                () =>
            {
                IAuthenticationManager authenticationManager = container.GetInstance <IAuthenticationManager>();
                IClaimsIdentityFactory claimsIdentityFactory = container.GetInstance <IClaimsIdentityFactory>();
                IPasswordHasher passwordHasher = container.GetInstance <IPasswordHasher>();
                IIdentityValidator <string> passwordIdentityValidator = container.GetInstance <IIdentityValidator <string> >();
                IIdentityValidator <User> userIdentityValidator       = container.GetInstance <IIdentityValidator <User> >();
                IUserRepository userRepository         = container.GetInstance <IUserRepository>();
                IUserTokenProvider userTokenProvider   = container.GetInstance <IUserTokenProvider>();
                IIdentityProvider userIdentityProvider = container.GetInstance <IIdentityProvider>();
                IUserTokenTwoFactorProvider userTokenTwoFactorProvider = container.GetInstance <IUserTokenTwoFactorProvider>();
                IDbContextScopeFactory dbContextScopeFactory           = container.GetInstance <IDbContextScopeFactory>();
                IMapper mapper = container.GetInstance <IMapper>();
                ILog logger    = container.GetInstance <ILog>();

                var userIdentityApplicationService = new UserIdentityApplicationService(
                    authenticationManager,
                    claimsIdentityFactory,
                    passwordHasher,
                    passwordIdentityValidator,
                    userIdentityValidator,
                    userRepository,
                    userTokenProvider,
                    userIdentityProvider,
                    userTokenTwoFactorProvider,
                    dbContextScopeFactory,
                    mapper,
                    logger);

                var authenticationService = container.GetInstance <IAuthenticationService>();
                userIdentityApplicationService.RegisterTwoFactorAuthenticationProvider("Phone Code", new PhoneNumberTokenProvider(authenticationService, new SmsService()));
                userIdentityApplicationService.RegisterTwoFactorAuthenticationProvider("Email Code", new EmailTokenProvider(authenticationService, new EmailService()));

                return(userIdentityApplicationService);
            });

            container.Register <SecurityStampValidator>(
                () =>
            {
                IDbContextScopeFactory dbContextScopeFactory = container.GetInstance <IDbContextScopeFactory>();
                IClaimsIdentityFactory claimsIdentityFactory = container.GetInstance <IClaimsIdentityFactory>();
                IUserRepository userRepository     = container.GetInstance <IUserRepository>();
                IIdentityProvider identityProvider = container.GetInstance <IIdentityProvider>();

                var securityStampValidator = new SecurityStampValidator(dbContextScopeFactory, userRepository, claimsIdentityFactory, identityProvider);

                return(securityStampValidator);
            });

            container.RegisterMvcControllers(Assembly.GetExecutingAssembly());
            container.Verify();

            DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
            GlobalConfiguration.Configuration.DependencyResolver = new SimpleInjectorDependencyResolver(container);

            return(container);
        }
Ejemplo n.º 13
0
 public CustomCookieAuthenticationEvents(IIdentityValidator identityValidator)
 {
     _identityValidator = identityValidator ?? throw new ArgumentNullException(nameof(identityValidator));
 }
        public UserIdentityApplicationService(
            IAuthenticationManager authenticationManager,
            IClaimsIdentityFactory claimsIdentityFactory,
            IPasswordHasher passwordHasher,
            IIdentityValidator <string> passwordIdentityValidator,
            IIdentityValidator <User> userIdentityValidator,
            IUserRepository userRepository,
            IUserTokenProvider userTokenProvider,
            IIdentityProvider userIdentityProvider,
            IUserTokenTwoFactorProvider userTokenTwoFactorProvider,
            IDbContextScopeFactory dbContextScopeFactory,
            IMapper mapper,
            ILog logger)
            : base(dbContextScopeFactory, mapper, logger)
        {
            this.authenticationManager      = authenticationManager;
            this.claimsIdentityFactory      = claimsIdentityFactory;
            this.passwordHasher             = passwordHasher;
            this.passwordIdentityValidator  = passwordIdentityValidator;
            this.userIdentityValidator      = userIdentityValidator;
            this.userRepository             = userRepository;
            this.userTokenProvider          = userTokenProvider;
            this.userIdentityProvider       = userIdentityProvider;
            this.userTokenTwoFactorProvider = userTokenTwoFactorProvider;

            this.AuthenticationType                   = Infrastructure.Identity.Model.AuthenticationType.ApplicationCookie;
            this.UserLockoutEnabledByDefault          = true;
            this.DefaultAccountLockoutTimeSpan        = TimeSpan.FromMinutes(DefaultAccountLockoutTimeSpanInMinutes);
            this.MaxFailedAccessAttemptsBeforeLockout = DefaultMaxFailedAccessAttemptsBeforeLockout;
        }