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?