Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add User to Role ASP.NET Identity

I know the new Membership includes a "Simple Role Provider."

I can't find any help related to creating a user and assigning a role when the user is created. I've added a user which created the tables on the DB correctly. I see the AspNetRoles, AspNetUserRoles, and AspNetUsers tables.

I am wanting to assign a role from AspNetRoles to a user in AspNetUsers which the ID of both the role/user are to be stored in AspNetUserRoles.

I'm stuck on the programming part of where and how to do this when I create the user.

I have a dropdown list to select the role, but using the Entity CF along with the new ASP.NET Identity model I'm not sure how to take the ID of the selectedvalue from the dropdown and the UserID and assign the role.

like image 533
Brad Martin Avatar asked Oct 30 '13 16:10

Brad Martin


2 Answers

I found good answer here Adding Role dynamically in new VS 2013 Identity UserManager

But in case to provide an example so you can check it I am gonna share some default code.

First make sure you have Roles inserted.

enter image description here

And second test it on user register method.

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
    if (ModelState.IsValid)
    {
        var user = new ApplicationUser() { UserName = model.UserName  };

        var result = await UserManager.CreateAsync(user, model.Password);
        if (result.Succeeded)
        {
            var currentUser = UserManager.FindByName(user.UserName); 

            var roleresult = UserManager.AddToRole(currentUser.Id, "Superusers");

            await SignInAsync(user, isPersistent: false);
            return RedirectToAction("Index", "Home");
        }
        else
        {
            AddErrors(result);
        }
    }

    // If we got this far, something failed, redisplay form
    return View(model);
}

And finally you have to get "Superusers" from the Roles Dropdown List somehow.

like image 190
Friend Avatar answered Oct 25 '22 14:10

Friend


I had the same challenge. This is the solution I found to add users to roles.

internal class Security
{
    ApplicationDbContext context = new ApplicationDbContext();

    internal void AddUserToRole(string userName, string roleName)
    {
        var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));

        try
        {
            var user = UserManager.FindByName(userName);
            UserManager.AddToRole(user.Id, roleName);
            context.SaveChanges();
        }
        catch
        {
            throw;
        }
    }
}
like image 28
Tarzan Avatar answered Oct 25 '22 13:10

Tarzan