How to add role and users in asp.net mvc 5?

I want to add user authorization and authentication in an asp.net mvc project. First, I am the base code of the Entity Framework. Now I want to create a default user role and a default role for him. To do this, I want to create an administrator role, but this prevents me from having the user and role Named admin and Admin Exists already. But when I see databases in my table, such as AspNetUSers, Role, etc., I did not find any Admin name there. So how can I do this?

If the administrator role and users are built-in, then where is the password. And also, how can I create some other default users and roles every time my application starts first.

I use MVC 5, not mvc 4. There are differences for both of these two.

Thanks,

Abdus Salam Azad

+2
source share
1 answer

Since no one answered your question, I would add code that shows how to do this from the Seed method when migrating. This code is used to seed the initial user in the database as an administrator. 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); } } 
+3
source

All Articles