CodexBloom - Programming Q&A Platform

ASP.NET Core 6: Custom Authorization Filter Not Triggering for Claims-Based Users

πŸ‘€ Views: 75 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-14
asp.net-core authorization claims csharp

I'm attempting to set up I've looked through the documentation and I'm still confused about I'm working on an ASP.NET Core 6 API and implemented a custom authorization filter to restrict access based on specific claims. However, it seems that the filter is not being triggered for users who have the required claims. I've tried debugging but I'm not able to find where it goes wrong. Here’s my custom authorization filter implementation: ```csharp public class ClaimsAuthorizeAttribute : TypeFilterAttribute { public ClaimsAuthorizeAttribute(string claimType, string claimValue) : base(typeof(ClaimsAuthorizeFilter)) { Arguments = new object[] { claimType, claimValue }; } } public class ClaimsAuthorizeFilter : IAuthorizationFilter { private readonly string _claimType; private readonly string _claimValue; public ClaimsAuthorizeFilter(string claimType, string claimValue) { _claimType = claimType; _claimValue = claimValue; } public void OnAuthorization(AuthorizationFilterContext context) { var user = context.HttpContext.User; if (!user.Identity.IsAuthenticated || !user.HasClaim(c => c.Type == _claimType && c.Value == _claimValue)) { context.Result = new ForbidResult(); } } } ``` I applied the filter to my controller like this: ```csharp [ClaimsAuthorize("Permission", "CanViewReports")] public class ReportsController : ControllerBase { [HttpGet] public IActionResult GetReport() { return Ok(); } } ``` When testing with a user who has the claim "Permission" with the value "CanViewReports", I expected them to access the `GetReport` action, but it always returns a `403 Forbidden`. I've checked the claims in the `HttpContext.User.Claims`, and it appears correct during debugging: ```csharp var claims = User.Claims.Select(c => new { c.Type, c.Value }).ToList(); ``` The claims list shows that the user does indeed possess the required permission, yet the filter denies access. I also confirmed that the authentication system is configured correctly using JWT bearer tokens, and there are no issues with user authentication. I would appreciate any insights on what might be causing this scenario. Is there something specific I might be missing in how the filter interacts with the claims? Any advice on debugging such scenarios would also be greatly helpful. For context: I'm using Csharp on Linux. Any help would be greatly appreciated! I'd really appreciate any guidance on this. This is part of a larger mobile app I'm building. What's the best practice here?