I would like to create some test users for my ASP.net MVC application. The version of identity is 2.2.1
My code generates users nicely, but I would like assign passwords that would allow these test accounts to login. So I beleive I need to call the same hashing function used when users are created the normal way.
My code is
ApplicationDbContext db = new ApplicationDbContext();
...
for (var i=0; i<100; i++)
{
var name = "User" + i;
var user = db.Users.FirstOrDefault(u => u.UserName == name);
if (user == null)
{
user = new ApplicationUser() {
UserName = name,
Email = name + "@" + name + "." + name,
PasswordHash = ?????hash of name ?????
};
db.Users.Add(user);
db.SaveChanges();
}
}
yes, i am trying for a password of User1 for User1, and User2 for User2 and so on.
Regards, John
The UserManager
will create the accounts. Assuming you are using the default Identity framework template There should be an ApplicationUserManager
derived from UserManager<ApplicationUser>
All the necessary configuration should already be in that class.
public async Task CreateTestUsers() {
var db = new ApplicationDbContext();
var userStore = new UserStore<ApplicationUser>(db);
var userManager = new ApplicationUserManager(userStore);
for (var i = 1; i <= 100; i++) {
var username = "User" + i;
var user = db.Users.FirstOrDefault(u => u.UserName == username);
if (user == null) {
user = new ApplicationUser() {
UserName = username,
Email = username + "@" + username + "." + username,
EmailConfirmed = true,
LockoutEnabled = false
};
var password = username;
var result = await userManager.CreateAsync(user, password);
}
}
}
That should then create the test users just as in the normal way with passwords all hashed and ready for testing.