I am trying to use the Authorize
attribute to validate a user's roles, but it never actually checks the role (any call with any role will go through successfully). Here, I just put in a check for a role named Temp
, which is not on the token I'm testing with, which is also confirmed by the code below also reading out the roles from the claims itself.
In my Program.cs
, I have AddAuthentication()
, AddMvc()
(calls AddAuthentication()
), UseAuthentication()
, and UseAuthorization()
called in that order, which I understand to be correct. I don't think I need any custom authorization handler, since checking roles should be pretty standard...
I don't do any additional setup, like for policies, since I'm not using policies and I'm only checking by roles.
I don't have [AllowAnonymous]
on my controller definition.
What else could I be missing here?
[HttpGet]
[Route("temp")]
[Authorize(Roles = "Temp")]
public ActionResult Temp()
{
var roles = this.IdentityService.GetRoles();
return this.Content(string.Join(",", roles));
}
public List<string> GetRoles()
{
var roles = new List<string>();
if (this.context.HttpContext != null &&
this.context.HttpContext.User.HasClaim(c => c.Type == "roles"))
{
roles.AddRange(this.context.HttpContext.User.Claims.Where(c => c.Type == "roles").Select(c => c.Value));
}
return roles;
}
I ended up just using a custom claims validator found in this post: How do you create a custom AuthorizeAttribute in ASP.NET Core?