问题
I want to add User authorization and authentication in asp.net mvc project. I am Entity Framework Code First. Now I want to create some default user and default role for it. For this I want to create a Admin Role, but it is preventing me that User and Role Named admin and Admin Exists already. But when I see in my Database Table such as AspNetUSers , Role etc. there I did not find any named Admin. So how can I do this?
If the admin role and users are built in, so where is the password. And also how can I create some other default users and roles each time when my application is running first.
I am using MVC 5 ,not mvc 4. There are difference for both of these two.
Thanks,
Abdus Salam Azad
回答1:
Since no one ever answered your question, I though I would add some code that shows how to do this from the Seed method on a migration. This code is used to seed an initial user in the database with an admin role. In my case, only the 'admin' user can add new users to the site.
protected override void Seed(PerSoft.Marketing.Website.Models.ApplicationDbContext context)
{
const string defaultRole = "admin";
const string defaultUser = "someUser";
// This check for the role before attempting to add it.
if (!context.Roles.Any(r => r.Name == defaultRole))
{
context.Roles.Add(new IdentityRole(defaultRole));
context.SaveChanges();
}
// This check for the user before adding them.
if (!context.Users.Any(u => u.UserName == defaultUser))
{
var store = new UserStore<ApplicationUser>(context);
var manager = new UserManager<ApplicationUser>(store);
var user = new ApplicationUser { UserName = defaultUser };
manager.Create(user, "somePassword");
manager.AddToRole(user.Id, defaultRole);
}
else
{
// Just for good measure, this adds the user to the role if they already
// existed and just weren't in the role.
var user = context.Users.Single(u => u.UserName.Equals(defaultUser, StringComparison.CurrentCultureIgnoreCase));
var store = new UserStore<ApplicationUser>(context);
var manager = new UserManager<ApplicationUser>(store);
manager.AddToRole(user.Id, defaultRole);
}
}
来源:https://stackoverflow.com/questions/22801862/how-to-add-role-and-users-in-asp-net-mvc-5