0

I created a web API 2 application that used token-based authentication system. I used this tutorial to implement the authentication to the application.

Then I added the roles to the system by using seed method.

        protected override void Seed(TBA.Models.AuthContext context)
        {
            if (!context.Roles.Any(r => r.Name == "SuperAdmin"))
            {
                var store = new RoleStore<IdentityRole>(context);
                var manager = new RoleManager<IdentityRole>(store);
                var role = new IdentityRole { Name = "SuperAdmin" };

                manager.Create(role);
            }
        }

Then I added the user to the user role.

        public async Task<IdentityResult> RegisterUser(UserModel userModel)
        {
            IdentityUser user = new IdentityUser
            {
                UserName = userModel.UserName
            };

            var result =  await _userManager.CreateAsync(user, userModel.Password);
            await _userManager.AddToRoleAsync(user.Id, userModel.UserRole);
            return result;
        }

Then I try to access to below end-point.

        [Authorize(Roles = "SuperAdmin")]
        [Route("GetBySuperAdmin")]
        public IHttpActionResult GetBySuperAdmin()
        {
            return Ok("Get By Super Admin");
        }

It gives me below error message.

"message": "Authorization has been denied for this request."

What should I change to make this correct? How to check role before accessing the end-point in Web API 2 application?

NoughT
  • 675
  • 4
  • 20
  • 39
  • Are You sure that userModel.UserRole is "SuperAdminę Can You check in DB in table UserRoles that this method is adding correct role? – garret Mar 15 '18 at 11:58

1 Answers1

0

After adding user to role, You have to log out and then log in again (generate new token).

Tokens have information about user's role, so after changing roles You have to refresh token, to have information about new roles.

garret
  • 1,134
  • 8
  • 16
  • can You check if You add proper ID in: await _userManager.AddToRoleAsync(user.Id, userModel.UserRole); ? – garret Mar 15 '18 at 11:50
  • @NoughT And check (in action with [AllowAnonymous] attribute) method: User.IsInRole("SuperAdmin"); And User.Identity.Name to make sure that You are logged as correct user, and identity can see users role. – garret Mar 15 '18 at 11:55
  • As you said, I checked User.IsInRole("SuperAdmin"). You are correct. the user doesn't have the role. What can I do now? – NoughT Mar 16 '18 at 02:54
  • I was able to fix the issue. https://stackoverflow.com/questions/26589466/how-can-i-get-a-users-role-inside-a-webapi-method-without-a-lookup-to-the-aspnet – NoughT Mar 16 '18 at 03:40