Search code examples
asp.net-web-apiasp.net-mvc-5visual-studio-2015asp.net-roles

MVC 5 Roles Out-of-the-box


Grettings. I see a thousand of questions and i lost on every one of them... So... Basically i start a new project on VS (WebAPI) with Authentication. I put the token on the header and the methods with

[Authorize]

works fine. Later i add a two roles into the table dbo.AspNetRoles (admin and users) and to one user i add the relationship in the table dbo.AspNetUserRoles like this:

USER ID    |    Roleid
-----------------------
1d156e98-fc8b-4dcb-8dba-f7c66131f488  |  1001

So, when i try to put this:

[Authorize(role="admin")]

Dont work... The request is denied. What i need to do exactly?

Thanks


Solution

  • So at the end i use this following code to resolve this:

    public class DAO
    {
        public static void addRoleToUser(ApplicationUser user, string role)
        {
            // EL SIGUIENTE CODIGO AGREGA AL USUARIO UN ROL
            ApplicationDbContext context = new ApplicationDbContext(); 
            var userStore = new UserStore<ApplicationUser>(context);
            var userManager = new UserManager<ApplicationUser>(userStore);
            userManager.AddToRole(user.Id,role);
        }
    }
    

    This sync the role to the user and the context db. In the controller after register a new user automatically adds the rol "User" with the code:

    // POST api/Account/Register
        [AllowAnonymous]
        [Route("Register")]
        public async Task<IHttpActionResult> Register(RegisterBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
    
            var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };
    
            IdentityResult result = await UserManager.CreateAsync(user, model.Password);
    
            if (!result.Succeeded)
            {
                return GetErrorResult(result);
            }
            // Codigo de Ali para agregar el rol "User" al usuario inmediatamente es creado
            DAO.addRoleToUser(user, "User");
            return Ok();
        }
    

    Thanks to dawidr to help me to go deep on this.