Пример #1
0
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType(typeof(AppUserManager)).As(typeof(IApplicationUserManager)).InstancePerRequest();
            builder.RegisterType(typeof(AppRoleManager)).As(typeof(IApplicationRoleManager)).InstancePerRequest();
            builder.RegisterType(typeof(AppSignInManager)).As(typeof(IApplicationSignInManager)).InstancePerRequest();
            builder.RegisterType(typeof(ApplicationAuthenticationManager)).As(typeof(IApplicationAuthenticationManager)).InstancePerRequest();
            builder.RegisterType(typeof(ApplicationIdentityUser)).As(typeof(IUser <int>)).InstancePerRequest();

            builder.Register(b => b.Resolve <IEntitiesContext>() as DbContext).InstancePerRequest();

            builder.Register(b => IdentityFactory.CreateUserManager(b.Resolve <IEntitiesContext>() as ApplicationDbContext, Startup.DataProtectionProvider)).InstancePerRequest();
            builder.Register(b => IdentityFactory.CreateRoleManager(b.Resolve <IEntitiesContext>() as ApplicationDbContext));
            builder.Register(b => IdentityFactory.CreateSignInManager(b.Resolve <ApplicationUserManager>(), HttpContext.Current.GetOwinContext().Authentication)).InstancePerRequest();
            builder.Register(b => HttpContext.Current.GetOwinContext().Authentication).InstancePerRequest();


            //builder.RegisterType(typeof(ApplicationRole)).As(typeof(IRole<int>)).InstancePerRequest();

            //builder.Register(b =>
            //{
            //    var manager = IdentityFactory.CreateUserManager(b.Resolve<DbContext>());
            //    if (Startup.DataProtectionProvider != null)
            //    {
            //        manager.UserTokenProvider =
            //            new DataProtectorTokenProvider<ApplicationIdentityUser, int>(
            //                Startup.DataProtectionProvider.Create("ASP.NET Identity"));
            //    }
            //    return manager;
            //}).InstancePerHttpRequest();
        }
Пример #2
0
        public void Configuration(IAppBuilder app)
        {
            //Issuer – a unique identifier for the entity that issued the token (not to be confused with Entity Framework’s entities)
            //Secret – a secret key used to secure the token and prevent tampering
            var issuer = ConfigurationManager.AppSettings["issuer"];
            var secret = TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["secret"]);

            //Important note: The life-cycle of object instance is per-request. As soon as the request is complete, the instance is cleaned up.
            var dbContext = (UnitOfWork) new UnitOfWorkFactory().Create();

            app.CreatePerOwinContext <UnitOfWork>(() => dbContext);
            app.CreatePerOwinContext(() => IdentityFactory.CreateUserManager(dbContext));
            //Enable bearer authentication - this code adds JWT bearer authentication to the OWIN pipeline
            app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
            {
                AuthenticationMode           = AuthenticationMode.Active,
                AllowedAudiences             = new[] { "Any" },
                IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                {
                    new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
                }
            });

            //expose an OAuth endpoint so that the client can request a token (by passing a user name and password)
            app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp = true,                            //for debugging/PoC. Later disable insecure access
                TokenEndpointPath = new PathString("/oauth2/token"), //End-point
                Provider          = new CustomOAuthProvider(),       //use custom provider and formatter
                AccessTokenFormat = new MSIdentityJwtFormat()
            });
        }
Пример #3
0
        public static void CreateAdminUsers(AkureTrainingDbContext context)
        {
            const string password = "******";

            var users = new string[]
            {
                "*****@*****.**",
                "*****@*****.**",
                "*****@*****.**",
            };

            var applicationRoleManager = IdentityFactory.CreateRoleManager(context);
            var applicationUserManager = IdentityFactory.CreateUserManager(context);

            Array.ForEach(users, customerID =>
            {
                IdentityResult identityResult;

                var user = applicationUserManager.FindByNameAsync(customerID).Result;

                if (user == null)
                {
                    user = new ApplicationIdentityUser {
                        UserName = customerID, Email = customerID
                    };
                    identityResult = applicationUserManager.CreateAsync(user, password).Result;

                    if (!identityResult.Succeeded)
                    {
                        identityResult = applicationUserManager.SetLockoutEnabledAsync(user.Id, false).Result;
                    }
                }

                var roleResult = applicationRoleManager.RoleExistsAsync("ADMIN");

                if (!roleResult.Result)
                {
                    identityResult = applicationRoleManager.CreateAsync(new ApplicationIdentityRole {
                        Name = "ADMIN"
                    }).Result;
                }

                var isInRole = applicationUserManager.IsInRoleAsync(user.Id, "ADMIN");

                if (user != null && !isInRole.Result)
                {
                    identityResult = applicationUserManager.AddToRoleAsync(user.Id, "ADMIN").Result;
                }

                //validate Email
                if (user != null)
                {
                    var token = applicationUserManager.GenerateEmailConfirmationToken(user.Id);
                    applicationUserManager.ConfirmEmail(user.Id, token);
                }
            });
        }
Пример #4
0
        //Create [email protected] with password=Admin@123456 in the Admin role
        public void InitializeIdentityForEF(AspnetIdentityWithOnionContext db)
        {
            // This is only for testing purpose
            const string name     = "*****@*****.**";
            const string password = "******";
            const string roleName = "Admin";
            var          applicationRoleManager = IdentityFactory.CreateRoleManager(db);
            var          applicationUserManager = IdentityFactory.CreateUserManager(db);
            //Create Role Admin if it does not exist
            var role = applicationRoleManager.FindByName(roleName);

            if (role == null)
            {
                role = new ApplicationIdentityRole {
                    Name = roleName
                };
                applicationRoleManager.Create(role);
            }

            var user = applicationUserManager.FindByName(name);

            if (user == null)
            {
                user = new ApplicationIdentityUser {
                    UserName = name, Email = name
                };
                applicationUserManager.Create(user, password);
                applicationUserManager.SetLockoutEnabled(user.Id, false);
            }

            // Add user admin to Role Admin if not already added
            var rolesForUser = applicationUserManager.GetRoles(user.Id);

            if (!rolesForUser.Contains(role.Name))
            {
                applicationUserManager.AddToRole(user.Id, role.Name);
            }
            var context = new AspnetIdentityWithOnionContext("name=AppContext", new DebugLogger());
            var image   = new Image {
                Path = "http://lorempixel.com/400/200/"
            };

            context.Set <Image>().Add(image);
            for (var i = 0; i < 100; i++)
            {
                context.Set <Product>().Add(new Product {
                    Name = "My Product", Description = "My Product", Image = image
                });
            }
            context.SaveChanges();
        }
        public void InitializeIdentityForEF(ApplicationDbContext db)
        {
            const string name     = "*****@*****.**";
            const string password = "******";

            string[] roleNames = new String[] { "ADMIN", "STAFF", "CUSTOMER" };
            var      applicationRoleManager = IdentityFactory.CreateRoleManager(db);
            var      applicationUserManager = IdentityFactory.CreateUserManager(db);

            //Create Role Admin if it does not exist
            Array.ForEach(roleNames, r =>
            {
                if (!applicationRoleManager.RoleExistsAsync(r).Result)
                {
                    applicationRoleManager.CreateAsync(new ApplicationIdentityRole {
                        Name = r
                    });
                }
            });

            var user = applicationUserManager.FindByNameAsync(name).Result;

            if (user == null)
            {
                user = new ApplicationIdentityUser {
                    UserName = name, Email = name
                };
                applicationUserManager.CreateAsync(user, password);
                applicationUserManager.SetLockoutEnabledAsync(user.Id, false);
            }

            // Add user admin to Role Admin if not already added
            if (!applicationRoleManager.RoleExistsAsync(roleNames[0]).Result&&
                !applicationUserManager.IsInRoleAsync(user.Id, roleNames[0]).Result)
            {
                applicationUserManager.AddToRoleAsync(user.Id, roleNames[0]);
            }

            if (!applicationRoleManager.RoleExistsAsync(roleNames[1]).Result&&
                !applicationUserManager.IsInRoleAsync(user.Id, roleNames[1]).Result)
            {
                applicationUserManager.AddToRoleAsync(user.Id, roleNames[1]);
            }

            //context.SaveChanges();
        }
Пример #6
0
 protected override void Load(ContainerBuilder builder)
 {
     builder.RegisterType(typeof(ApplicationUserManager)).As(typeof(IApplicationUserManager)).InstancePerRequest();
     builder.RegisterType(typeof(ApplicationRoleManager)).As(typeof(IApplicationRoleManager)).InstancePerRequest();
     builder.RegisterType(typeof(ApplicationIdentityUser)).As(typeof(IUser <int>)).InstancePerRequest();
     builder.Register(b =>
     {
         var manager = IdentityFactory.CreateUserManager(b.Resolve <DbContext>());
         if (Startup.DataProtectionProvider != null)
         {
             manager.UserTokenProvider =
                 new DataProtectorTokenProvider <ApplicationIdentityUser, int>(
                     Startup.DataProtectionProvider.Create("ASP.NET Identity"));
         }
         return(manager);
     }).InstancePerRequest();
     builder.Register(b => IdentityFactory.CreateRoleManager(b.Resolve <DbContext>())).InstancePerRequest();
     builder.Register(b => HttpContext.Current.GetOwinContext().Authentication).InstancePerRequest();
 }
Пример #7
0
        protected override void Seed(LuaBijouxContext context)
        {
            const string username = "******";
            const string password = "******";
            const string roleName = "Administrator";

            var applicationRoleManager = IdentityFactory.CreateRoleManager(context);
            var applicationUserManager = IdentityFactory.CreateUserManager(context);


            //Create Role Admin if it does not exist
            var role = applicationRoleManager.FindByName(roleName);

            if (role == null)
            {
                role = new ApplicationIdentityRole {
                    Name = roleName
                };
                applicationRoleManager.Create(role);
            }

            var user = applicationUserManager.FindByName(username);

            if (user == null)
            {
                user = new ApplicationIdentityUser {
                    UserName = username, Email = username
                };
                applicationUserManager.Create(user, password);
                applicationUserManager.SetLockoutEnabled(user.Id, false);
            }

            // Add user admin to Role Admin if not already added
            var rolesForUser = applicationUserManager.GetRoles(user.Id);

            if (!rolesForUser.Contains(role.Name))
            {
                applicationUserManager.AddToRole(user.Id, role.Name);
            }

            // var context = new LuaBijouxContext("name=AppContext", new DebugLogger());
            context.SaveChanges();
        }
Пример #8
0
        public static ApplicationIdentityUser CreateAdminUser(IPosDbContext context)
        {
            var applicationUserManager = IdentityFactory.CreateUserManager(context);

            string username = "******";
            string password = "******";

            ApplicationIdentityUser user = applicationUserManager.FindByNameAsync(username).Result;

            if (user != null)
            {
                return(user);
            }

            user = new ApplicationIdentityUser
            {
                UserName = username,
                Email    = username
            };


            if (IposConfig.UseMembership)
            {
                IposMembershipService.CreateUserAccount(new AppUserViewModel {
                    UserName = username, Password = password
                });
            }


            applicationUserManager.CreateAsync(user, password).Wait();
            applicationUserManager.SetLockoutEnabled(user.Id, false);
            applicationUserManager.Update(user);

            var isInRole = applicationUserManager.IsInRoleAsync(user.Id, IposRoleHelper.ADMIN);

            if (user != null && !isInRole.Result)
            {
                applicationUserManager.AddToRoleAsync(user.Id, IposRoleHelper.ADMIN).Wait();
            }
            return(user);
        }
        public void InitializeIdentityForEf(ApplicationDbContext db)
        {
            // This is only for testing purpose
            const string name     = "*****@*****.**";
            const string password = "******";
            const string roleName = "Admin";
            var          applicationRoleManager = IdentityFactory.CreateRoleManager(db);
            var          applicationUserManager = IdentityFactory.CreateUserManager(db);
            //Create Role Admin if it does not exist
            var role = applicationRoleManager.FindByName(roleName);

            if (role == null)
            {
                role = new ApplicationIdentityRole {
                    Name = roleName
                };
                applicationRoleManager.Create(role);
            }

            var user = applicationUserManager.FindByName(name);

            if (user == null)
            {
                user = new ApplicationIdentityUser {
                    UserName = name, Email = name
                };
                applicationUserManager.Create(user, password);
                applicationUserManager.SetLockoutEnabled(user.Id, false);
            }

            // Add user admin to Role Admin if not already added
            var rolesForUser = applicationUserManager.GetRoles(user.Id);

            if (!rolesForUser.Contains(role.Name))
            {
                applicationUserManager.AddToRole(user.Id, role.Name);
            }
            db.SaveChanges();
        }
Пример #10
0
        public void Register(ContainerBuilder builder, ITypeFinder typeFinder)
        {
            builder.Register(b =>
            {
                return(HttpContext.Current.Request.GetOwinContext().Get <IApplicationSignInManager>());
            }).As <IApplicationSignInManager>().InstancePerRequest();

            builder.RegisterType(typeof(ApplicationIdentityUser)).As(typeof(IUser <int>)).InstancePerRequest();

            builder.Register(b =>
            {
                var manager = IdentityFactory.CreateUserManager((IPosDbContext)b.Resolve <IEntitiesContext>());
                return(manager);
            }).InstancePerRequest();

            builder.Register(b => IdentityFactory.CreateRoleManager((IPosDbContext)
                                                                    b.Resolve <IEntitiesContext>())).InstancePerRequest();

            builder.Register(b =>
            {
                return(HttpContext.Current.Request.GetOwinContext().Get <IApplicationRoleManager>());
            }).As <IApplicationRoleManager>().InstancePerRequest();

            builder.Register(b =>
            {
                return(HttpContext.Current.Request.GetOwinContext().Get <IApplicationUserManager>());
            }).As <IApplicationUserManager>().InstancePerRequest();


            builder.Register(b =>
            {
                var manager = IdentityFactory.CreateUserManager((IPosDbContext)b.Resolve <IEntitiesContext>());
                return(manager);
            }).InstancePerRequest();

            builder.Register(b => IdentityFactory.CreateRoleManager((IPosDbContext)
                                                                    b.Resolve <IEntitiesContext>())).InstancePerRequest();
        }
Пример #11
0
 public UserRepository(UnitOfWork context)
 {
     _dbContext      = Guard.AgainstNull(context);
     _repositoryBase = new RepositoryBase(_dbContext);
     _userManager    = IdentityFactory.CreateUserManager(_dbContext);
 }
        //Create [email protected] with password=Admin@123456 in the Admin role
        public void InitializeIdentityForEF(AspnetIdentityWithOnionContext db)
        {
            // This is only for testing purpose
            const string name     = "*****@*****.**";
            const string password = "******";

            string[] roleName = new string[] { "Admin", "Anonim", "Manager", "User" };
            var      applicationRoleManager = IdentityFactory.CreateRoleManager(db);
            var      applicationUserManager = IdentityFactory.CreateUserManager(db);
            //Create Role Admin if it does not exist

            ApplicationIdentityRole role;

            foreach (var item in roleName)
            {
                role = new ApplicationIdentityRole {
                    Name = item
                };
                applicationRoleManager.Create(role);
                role = null;
            }
            //var role = applicationRoleManager.FindByName(roleName);
            //if (role == null)
            //{
            //    role = new ApplicationIdentityRole { Name = roleName };
            //    applicationRoleManager.Create(role);
            //}

            var user = applicationUserManager.FindByName(name);

            if (user == null)
            {
                user = new ApplicationIdentityUser {
                    UserName = name, Email = name
                };
                applicationUserManager.Create(user, password);
                applicationUserManager.SetLockoutEnabled(user.Id, false);
            }

            // Add user admin to Role Admin if not already added
            var rolesForUser = applicationUserManager.GetRoles(user.Id);

            foreach (var item in roleName)
            {
                if (!rolesForUser.Contains(item))
                {
                    applicationUserManager.AddToRole(user.Id, item);
                }
            }

            var context = new AspnetIdentityWithOnionContext("name=AppContext", new DebugLogger());
            //var image = new Image { Path = "http://lorempixel.com/400/200/" };
            //context.Set<Image>().Add(image);

            //context.Set<Category>().Add(new Category { Name = "Cameras", IsActive = true, Path = "6a81942d-d825-4c18-97ca-4a5a906c68ad.jpg" });
            //context.Set<Category>().Add(new Category { Name = "BagsCase", IsActive = true, Path = "49307dd0-7ada-4e12-b1e9-e5040269288f.jpg" });
            //context.Set<Category>().Add(new Category { Name = "Accessuare", IsActive = true, Path = "1c68860a-3b9a-4278-90ce-0b0237ec4898.jpg" });

            //context.Set<SubCategory>().Add(new SubCategory { Name = "SLR Cameras", })
            //for (var i = 0; i < 10; i++)
            //{
            //    context.Set<Product>().Add(new Product { Name = "My Product", Price = 35});

            //}
            //context.Set<Category>().Add(new Category { Name = "ForExample", IsActive = true });
            //context.SaveChanges();
        }
Пример #13
0
 private Program(ApplicationDbContext context)
 {
     UserManager = IdentityFactory.CreateUserManager(context);
     RoleManager = IdentityFactory.CreateRoleManager(context);
 }