Search code examples
c#asp.net-mvc-5asp.net-identity

Correct way of setting the role for user when he is registered with Identity


I have a question, I'm new to identity, but still i would like to know what would be the correct way of assigning role to a user when he is registering?

I have here a code:

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

            RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
            IdentityRole role = new IdentityRole("Admin");
            await RoleManager.CreateAsync(role);

            // Store Gender as Claim
            user.Claims.Add(new IdentityUserClaim() { ClaimType = ClaimTypes.Gender, ClaimValue = "Male" });
            //user.Roles.Add(new IdentityUserRole() { RoleId=role.Id, UserId=user.Id });
            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                //await UserManager.AddToRoleAsync(user.Id, "Admin");

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

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

This is just a test code, but basically if i use method UserManager.AddToROleAsync( ...) it works, BUT, it only happens after the user is added, so basically i do twice the roundtrip to database.

I tried doing it with user.Roles.Add(...) but i get an error when running it.

So my question would be what is the most efficient and correct way of doing it?


Solution

  • I don't know if there's a better way. I normally to it the same way as you do, first creating the role (if it doesn't exist), then creating the user, and as a last step adding the user to the role.

    To use user.Roles.Add(...) the role must be present. The reason is the database (in this case Entity Framework and SQL Server). When looking closer at the Identity database you'll see that there is a relationship between the AspNetRoles and AspNetUsers table through the AspNetUserRoles table which has the UserId and the RoleId as a key. That means you can't add a user to a role when the user does not exist yet (and vice versa). So in my opinion you have to do twice the roundtrip (if you don't directly work on the context).