Adding Role dynamically in new VS 2013 Identity UserManager
Asked Answered
M

1

6

I created a new MVC application in the new VS2013 IDE. I added the following to the Login Action on the AccountController as I wanted to create a default user dynamically:

var admin = new ApplicationUser() { UserName = "administrator" };
var result = UserManager.Create(admin, "administrator");

This works great, I then wanted to put this default user into a new default role:

user = UserManager.FindByName("administrator");
var roleresult = UserManager.AddToRole(user.Id,"admin");

The second line errors because obviously it can't find the role "admin" as it doesn't exist yet, but I can't find a relevant method on the UserManager to do so. Where can I find the method to add roles dynamically?

Megilp answered 23/10, 2013 at 13:36 Comment(0)
A
16

Here is how I did it. I have a Dictionary userRoles with preauthorized {userName, role} key - value pairs :

private void setRoles()
{
    using(var rm = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext())))
    using(var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())))
        foreach (var item in userRoles)
        {
            if (!rm.RoleExists(item.Value))
            {
                var roleResult = rm.Create(new IdentityRole(item.Value));
                if (!roleResult.Succeeded)
                    throw new ApplicationException("Creating role " + item.Value + "failed with error(s): " + roleResult.Errors);
            }
            var user = um.FindByName(item.Key);
            if (!um.IsInRole(user.Id, item.Value))
            {
                var userResult = um.AddToRole(user.Id, item.Value);
                if (!userResult.Succeeded)
                    throw new ApplicationException("Adding user '" + item.Key + "' to '" + item.Value + "' role failed with error(s): " + userResult.Errors);
            }
        }
}
Arronarrondissement answered 23/10, 2013 at 20:17 Comment(3)
Perfect thank you. It was the RoleManager that I needed. Is defining Roles on Controllers any different now?Megilp
You are welcome, user1166905. Creating a role is quite simple, it is shown on the line "var roleResult = rm.Create(new IdentityRole(item.Value));"Arronarrondissement
Thanks I meant defining them on Controllers i.e. [Authorize(Roles="admin")] but already tested and is the same.Megilp

© 2022 - 2024 — McMap. All rights reserved.