In my project, I have number of APIs using JWT token which are decorated with [Authorize]
attribute and it run well.
[HttpPost]
[Authorize(Roles = "Administrator")]
public IActionResult GetCustomers()
{
return Ok();
}
If I provide null, wrong JWT token or JWT token with not Administrator role, it return response like picture below:
But I want to custom response like that:
{
"StatusCode" : 401,
"message": "You need Administrator role"
}
And I follow to this reference to custom authorize attribute.
My custom:
public class ClaimRequirementAttribute : TypeFilterAttribute
{
public ClaimRequirementAttribute(string claimType, string claimValue) : base(typeof(CustomAuthorization))
{
Arguments = new object[] { new Claim(claimType, claimValue) };
}
}
public class CustomAuthorization : IAuthorizationFilter
{
readonly Claim _claim;
public CustomAuthorization(Claim claim)
{
_claim = claim;
}
public void OnAuthorization(AuthorizationFilterContext context)
{
var hasClaim = context.HttpContext.User.Claims.Any(c => c.Type == _claim.Type && c.Value == _claim.Value);
if (!hasClaim)
{
context.Result = new ForbidResult($"You need {_claim.Value} role");
}
}
}
And my controller:
[HttpPost]
[ClaimRequirement(ClaimTypes.Role, "Administrator")]
public IActionResult GetCustomers()
{
return Ok();
}
But I have 2 problems:
The first problem is that if I provide null, wrong JWT token or JWT token with not administrator role, I have this error:
And the second is whether there is a simple way to solve it ?
Thanks for your attention.
Edit: the first question i solved it, the solution in my comment