CodexBloom - Programming Q&A Platform

How to correctly implement user-specific resource access in ASP.NET Core with policies?

👀 Views: 0 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-12
asp.net-core authorization policies csharp

I'm relatively new to this, so bear with me. I've searched everywhere and can't find a clear answer. I've been banging my head against this for hours... I'm facing an issue with implementing granular resource access control in my ASP.NET Core 6 application using policies. I have a requirement where users can only access certain resources based on their roles and specific attributes. I tried creating a custom authorization requirement and handler, but it seems that my policies are not being evaluated correctly. I have the following code: ```csharp public class ResourceAccessRequirement : IAuthorizationRequirement { public string ResourceId { get; } public ResourceAccessRequirement(string resourceId) { ResourceId = resourceId; } } public class ResourceAccessHandler : AuthorizationHandler<ResourceAccessRequirement> { protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, ResourceAccessRequirement requirement) { var userId = context.User.FindFirst(ClaimTypes.NameIdentifier)?.Value; // Simulate a check against a database or service if (userId == "123" && requirement.ResourceId == "abc") { context.Succeed(requirement); } return Task.CompletedTask; } } ``` I've registered the handler in `Startup.cs`: ```csharp services.AddAuthorization(options => { options.AddPolicy("ResourceAccess", policy => policy.Requirements.Add(new ResourceAccessRequirement("abc"))); }); services.AddSingleton<IAuthorizationHandler, ResourceAccessHandler>(); ``` And I'm applying the policy in my controller like this: ```csharp [Authorize(Policy = "ResourceAccess")] public IActionResult GetResource() { return Ok("You have access to this resource!"); } ``` However, when I test it with a user who should have access, I still receive a 403 Forbidden response. I verified that the user is authenticated and the claims are being populated correctly. Is there something I'm missing in the configuration or the policy evaluation? Any insights on how to troubleshoot this? Thanks! I'm working on a CLI tool that needs to handle this. How would you solve this? This is part of a larger web app I'm building. What's the best practice here?