Create Users and Roles using Asp.net mvc - asp.net-mvc

I used this code to create default Users and Roles in the Startup file.
public void CreateDefaultRolesAndUsers()
{
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(db));
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
IdentityRole role = new IdentityRole();
if(!roleManager.RoleExists("Admins"))
{
role.Name = "Admins";
roleManager.Create(role);
ApplicationUser user = new ApplicationUser();
user.UserName = "Ahmed";
user.Email = "ahmed#live.com";
var Check = userManager.Create(user, "Ahmed*90");
if(Check.Succeeded)
{
userManager.AddToRole(user.Id, "Admins");
}
}
}
The Role is created but the User does not ..where is the problem??

Related

create user in migration Up() using Identity Framework

I have added a migration to create a user but the code hangs when it hits userRepo.Create(...) and within this method at _userManager.Create(...)
using (UserRepository userRepo = new UserRepository())
{
User adminUser = new User() { IsActive = true, UserName =
"admin#testing.com", CompanyId = 1, Password =
"admintesting" };
adminUser.Role = new Models.Security.Role() { Id = 2 };
userRepo.Create(adminUser);
}
Create method is below
public IdentityResult Create(Model.User user)
{
var userEntity = Mapper.Map<Entity.Security.User>(user);
_dbContext.Set<Entity.Security.User>().Add(userEntity);
var result = _userManager.Create(userEntity, userEntity.Password);
DetachAllEntities();
return result;
}
_dbContext is inherited from IdentityDbContext and instantiated accordingly
UserManager<Entity.Security.User, int> _userManager = new UserManager<Entity.Security.User, int>(new UserStore<Entity.Security.User, Entity.Security.Role, int, Entity.Security.UserLogin, Entity.Security.UserRole, Entity.Security.UserClaim>(_dbContext));
The equivalent async method works elsewhere in the application but I would like the non-async for the migration sake. Any help is highly appreciated.

Seed Roles (RoleManager vs RoleStore)

Through looking at the posts here, I've seen two different ways of creating ASP.NET Identity roles through Entity Framework seeding. One way uses RoleManager and the other uses RoleStore. I was wondering if there is a difference between the two. As using the latter will avoid one less initialization
string[] roles = { "Admin", "Moderator", "User" };
// Create Role through RoleManager
var roleStore = new RoleStore<IdentityRole>(context);
var manager = new RoleManager<IdentityRole>(roleStore);
foreach (string role in roles)
{
if (!context.Roles.Any(r => r.Name == role))
{
manager.Create(new IdentityRole(role));
}
// Create Role through RoleStore
var roleStore = new RoleStore<IdentityRole>(context);
foreach (string role in roles)
{
if (!context.Roles.Any(r => r.Name == role))
{
roleStore.CreateAsync(new IdentityRole(role));
}
}
In your specific case, using both methods, you achieve the same results.
But, the correct usage would be:
var context = new ApplicationIdentityDbContext();
var roleStore = new RoleStore<IdentityRole>(context);
var roleManager = new RoleManager<IdentityRole>(roleStore);
string[] roles = { "Admin", "Moderator", "User" };
foreach (string role in roles)
{
if (!roleManager.RoleExists(role))
{
roleManager.Create(new IdentityRole(role));
}
}
The RoleManager is a wrapper over a RoleStore, so when you are adding roles to the manager, you are actually inserting them in the store, but the difference here is that the RoleManager can implement a custom IIdentityValidator<TRole> role validator.
So, implementing the validator, each time you add a role through the manager, it will first be validated before being added to the store.

How to create New user identity out side from Account controller?

I have merged my database with MVC asp.net Identity database and i want to creat a new user using asp.net identity from other controller ,but i could not successfully add the user even my code work without error this is the code:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Email,EmailConfirmed,Password,SecurityStamp,PhoneNumber,PhoneNumberConfirmed,TwoFactorEnabled,LockoutEndDateUtc,LockoutEnabled,AccessFailedCount,UserName")] AspNetUsers aspNetUsers)
{
if (ModelState.IsValid)
{
// ApplicationUserManager manager = new ApplicationUserManager(new UserStore<ApplicationUser>());
// var manager = HttpContext.Current.GetOwinContext().GetUserManager<UserManager<User>>();
var store = new UserStore<ApplicationUser>();
var manager = new ApplicationUserManager(store);
var user = new ApplicationUser() { Email = aspNetUsers.Email, UserName = aspNetUsers.UserName };
var result= manager.CreateAsync(user, aspNetUsers.PasswordHash);
manager.Create(user, aspNetUsers.Password);
// db.AspNetUsers.Add(aspNetUsers);
// db.SaveChanges();
return RedirectToAction("Index");
}
return View(aspNetUsers);
}
var store = new UserStore<ApplicationUser>(new ApplicationDbContext());
ApplicationUserManager _userManager = new ApplicationUserManager(store);
var manger = _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
var user = new ApplicationUser() { Email = aspNetUsers.Email, UserName = aspNetUsers.UserName };
var usmanger= manger.Create(user, aspNetUsers.PasswordHash);

MVC 5 seeding users only works for email

I am working on a porject built on MVC5 and EF Code First.
I have multiple contexts, but the one I'm concered about here is the ApplicationDbContext which has the following configuration code:
namespace DX.DAL.Migrations.ApplicationDbMigrations
{
public class Configuration : DbMigrationsConfiguration<ApplicationDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
MigrationsDirectory = #"Migrations\ApplicationDbMigrations";
ContextKey = "DX.DAL.Context.ApplicationDbContext";
}
protected override void Seed(ApplicationDbContext context)
{
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
if (!roleManager.RoleExists("Admin"))
{
roleManager.Create(new IdentityRole("Admin"));
}
var user = new ApplicationUser { UserName = "John", Email = "j.doe#world.com" };
if (userManager.FindByName("John") != null) return;
var result = userManager.Create(user, "Password123#");
if (result.Succeeded)
{
userManager.AddToRole(user.Id, "Admin");
}
}
}
}
When I try and login with the email and password seeded above, I get the error:
Invalid login attempt
I wrote the following SQL Query:
SELECT * FROM AspNetUsers
And I see the following:
So the seed has been created. But why can't I login?
Also, I know that if I change the Username to be the same as the email, then it works and I can login. Must the username and email be the same for ASP.NET Membership in MVC 5 to work?
After trying so many different things, I went with LukeP's solution here.
I left Identity as it is and just added a new property called DisplayUsername and allowed the user to set that up on registration.

Can I use the Configuration.Seed method to an an initial ApplicationUser to an MVC database?

I know that we can initialise the database when doing a Entity Framework migration using the Seed method, as below.
protected override void Seed(CraigSheppardSoftware.Models.ApplicationDbContext context)
{
context.Users.AddOrUpdate(p => p.UserName,
new ApplicationUser { FullName = "System Admin", UserName="CssOp", UserRole = UserType.SystemAdmin,
LandlinePhone=new ComplexDataTypes.PhoneNumber(), MobilePhone= new ComplexDataTypes.PhoneNumber()
} );
context.SaveChanges();
}
The problem is that the when I try to use that user to login with, I can't as I dont know what the password is.
There is no password field on the database. I notice that there is a PasswordHash field and suspect that this is an encrypted password. How do I create a password hash ?
Use UserManager to create / update the user.
var manager = new UserManager<ApplicationUser>(
new UserStore<ApplicationUser>(context));
var user = manager.Find("CssOp", "ThePassword");
if (user == null)
{
user = new ApplicationUser { UserName = "CssOp", Email = "email#mail.com" };
manager.Create(user, "ThePassword");
}
else
{
user.Email = "newemail#mail.com";
manager.Update(user);
}

Resources