I'm having trouble getting some simple role based security to work in an ASP.NET MVC5 SPA in VS2017 Community.
Here's the top of my controller:
namespace ManagementWebSite.Controllers
{
[Authorize(Roles = "Administrator")]
public class SystemManagementController : ApiController
Controller works fine with no Authorize attribute, but I want to lock it down to an Administrator app role. I added the role to my test@test.com user like so in Startup.cs:
void ConfigureRolesandUsers()
{
ApplicationDbContext context = new ApplicationDbContext();
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
if (!roleManager.RoleExists("Administrator"))
{
var role = new IdentityRole();
role.Name = "Administrator";
roleManager.Create(role);
var user = userManager.FindByEmail("test@test.com");
if (user != null)
{
if (user.Roles.Where(b => b.RoleId == role.Id).Count() == 0)
{
userManager.AddToRole(user.Id, "Administrator");
}
}
}
}
Seems to get the role claim on login, but still, if I login as test@test.com and try to use the controller in the browser I get a 401 Unauthorized, and I'm not sure why because the user has the Administrator role and is getting the claim on login.
Logging out and back in, restarting VS, removing (and later re-adding) the RoleManager module didn't work.
So the next thing I tried was subclassing the AuthorizeAttribute like so:
public class RoleAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
}
protected override HttpValidationStatus OnCacheAuthorization(HttpContextBase httpContext)
{
return base.OnCacheAuthorization(httpContext);
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
return base.AuthorizeCore(httpContext);
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
base.HandleUnauthorizedRequest(filterContext);
}
}
And setting breakpoints on each method. None of the breakpoints get hit while trying to debug, but now the app lets it through, so I'm wondering what's going on and if it's even checking the role properly like it should. How do I debug when I need to see what's going on upstream from the controller action like this? Seems like the AuthorizeAttribute alone should just work without subclassing since it has a Roles property to use, is this not the case?