How to add role and Users in asp.net mvc 5?
Asked Answered
U

1

2

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

Ursuline answered 2/4, 2014 at 4:52 Comment(1)
Check this project : github.com/rustd/AspnetIdentitySampleDucharme
H
5

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);
    }
}
Helvetian answered 29/10, 2014 at 23:16 Comment(1)
When I use this method, the IdentityUserRoles table in the db only has values in two (of its four) fields. If I don't get all 4 fields populated then some other (built-in) code fails. Any ideas on this?Laudianism

© 2022 - 2024 — McMap. All rights reserved.