So I was trying to access the httpContext accessor to fetch the jwt token claims , But when i try to fetch the claims in my custom authroize class its come out to be empty and its IsAuthenticated flag is false
The sample code
public class Authorize : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext actionContext)
{
// Get role ID from claims
if (!int.TryParse(actionContext.HttpContext.User?.FindFirstValue("AcmRoleId"), out int roleId))
{
actionContext.Result = new ContentResult
{
StatusCode = (int)HttpStatusCode.BadRequest,
Content = "Role ID not found in token"
};
return;
}
}
THis is how i would be using this
[@Authorize(ModuleName = "Dashboard", Read = (int)ModulePrivileges.Own)]
I was expecting the HttpContext to contain the jwt token claims don't know why it don't contain any claim if their is a alternative let me know
You need to implement AuthorizeAttribute
and IAuthorizationFilter
for custom Authorization attribute. Such as following:
public class CustomAuthorizeAttribute : AuthorizeAttribute, IAuthorizationFilter
{
private readonly string _role;
public CustomAuthorizeAttribute(string role)
{
_role = role;
}
public void OnAuthorization(AuthorizationFilterContext context)
{
var user = context.HttpContext.User;
// Custom authorization logic
if (!user.Identity.IsAuthenticated || !user.IsInRole(_role))
{
context.Result = new ForbidResult();
}
}
}
Then you could use [CustomAuthorize("AcmRole")]