Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mass Insertion of Users/Passwords into ASP.Identity Users and Memberships Tables

I'd like to insert over 1,000 usernames and passwords into the ASP.Identity Users and Memberships table. Ideally, I would like to encrypt the passwords when they are inserted. Can this be done with T-SQL or do I have to use some code in C# to loop through a routine that will encrypt the passwords and insert the usernames and possibly other information? An example of this would be appreciated.

like image 207
user1966800 Avatar asked Mar 20 '14 02:03

user1966800


1 Answers

Ok, So I found a way to bulk insert in AspNet Identity Tables Without Performance Hit.

public void CreateBulkIdentityUsers(List<string> userNames)
    {
        using (ApplicationDbContext context = new ApplicationDbContext())
        {
            var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));

            var users = context.Users.Where(u => userNames.Contains(u.UserName)).ToList();

            PasswordHasher passwordHasher = new PasswordHasher();

            foreach (var userName in userNames)
            {
                var user = users.Where(u => u.UserName == userName).FirstOrDefault();

                if (user == null)
                {
                    user = new ApplicationUser()
                    {
                        UserName = userName,
                        EmailConfirmed = false,
                        PhoneNumberConfirmed = false,
                        TwoFactorEnabled = false,
                        LockoutEnabled = false,
                        PasswordHash = passwordHasher.HashPassword("Password@123"),
                        SecurityStamp = Guid.NewGuid().ToString().ToLower()
                    };

                    context.Users.Add(user);
                }
            }
            context.SaveChanges();
        }
    }
  1. getting all users before the loop. so that we can check if that user already exists in the database.

  2. initilizing PasswordHasher to hash Password.

  3. Finding a User if found then just skip it. if not found then create a new user with some password.

Hope, This helps someone. :)

like image 63
Jawand Singh Avatar answered Sep 18 '22 02:09

Jawand Singh