Round #483
09 May 2026, 19:40· csharp· qwen2.5-coder-7b-instruct· r13-clean-hints
- Complexity
- band 1
- ZP / UO / OBS
- 3 / 5 / 3
- Journey weight
- 692
- Lightshift ΔL
- +0.00
Prompt
Implement resource-based authorization using IAuthorizationHandler
Zero-point index (what the engine surfaced)
ZPI-ZPI-0007 | 2026-05-09T19:40:03Z
Implement resource-based authorization using IAuthorizationHandler
ZERO POINT — 3 entries (structural invariants)
● hsl(178.91, 100%, 27%) IAuthorizationHandler [contract]
● hsl(14.32, 100%, 27%) IAuthorizationRequirement [contract]
● hsl(349.17, 100%, 27%) AuthorizationHandler<TRequirement> [contract]
UNOBSERVED — 5 entries (implied truths)
○ hsl(27.69, 100%, 50%) async [feature]
○ hsl(49.23, 100%, 50%) try [feature]
○ hsl(31.38, 100%, 42%) Scoped registration [function]
○ hsl(44.31, 100%, 42%) IOptions of T binding [function]
○ hsl(112.62, 100%, 30%) Token validation parameters [function]
OBSERVED — 3 entries (explicit in request)
◉ hsl(85.13, 100%, 50%) using [feature]
◉ hsl(234.87, 100%, 50%) using [feature]
◉ hsl(121.85, 100%, 14%) Resource-based authorization [function]
COMPLEXITY │ 11 entries │ spread: 207° │ band: MEDIUM
Baseline response (no ZPI)
To implement resource-based authorization in C#, you can use the `IAuthorizationHandler` interface provided by ASP.NET Core. This allows you to define custom authorization logic that checks if a user has permission to access a specific resource.
Here's a step-by-step guide on how to set up resource-based authorization:
1. **Define the Authorization Policy**: Create an authorization policy that specifies the requirements for accessing a resource.
2. **Implement the IAuthorizationHandler**: Create a class that implements `IAuthorizationHandler` and contains the logic to check if the user has permission to access the resource.
3. **Register the Handler and Policy in Startup.cs**: Register the custom handler and policy with the authorization system.
### Step 1: Define the Authorization Policy
First, define an authorization policy that specifies the requirements for accessing a resource. You can do this in your `Startup.cs` file or any other configuration class.
```csharp
public void ConfigureServices(IServiceCollection services)
{
// Add authorization services to the service container.
services.AddAuthorization(options =>
{
options.AddPolicy("AccessResource", policy =>
policy.RequireClaim("ResourceAccess", "Allowed"));
});
// Other service registrations...
}
```
### Step 2: Implement the IAuthorizationHandler
Create a class that implements `IAuthorizationHandler` and contains the logic to check if the user has permission to access the resource.
```csharp
using Microsoft.AspNetCore.Authorization;
using System.Threading.Tasks;
public class ResourceAccessHandler : AuthorizationHandler<ResourceAccessRequirement>
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, ResourceAccessRequirement requirement)
{
// Check if the user has the required claim to access the resource.
if (context.User.HasClaim(c => c.Type == "ResourceAccess" && c.Value == "Allowed"))
{
context.Succeed(requirement);
}
return Task.CompletedTask;
}
}
```
### Step 3: Register the Handler and Policy in Startup.cs
Register the custom handler and policy with the authorization system.
```csharp
public void ConfigureServices(IServiceCollection services)
{
// Add authorization services to the service container.
services.AddAuthorization(options =>
{
options.AddPolicy("AccessResource", policy =>
policy.RequireClaim("ResourceAccess", "Allowed"));
});
// Register the custom handler.
services.AddSingleton<IAuthorizationHandler, ResourceAccessHandler>();
// Other service registrations...
}
```
### Step 4: Apply the Authorization Policy to a Controller or Action
Finally, apply the authorization policy to a controller or action using the `[Authorize]` attribute.
```csharp
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[controller]")]
public class ResourceController : ControllerBase
{
[HttpGet("{id}")]
[Authorize(Policy = "AccessResource")]
public IActionResult GetResource(int id)
{
// Logic to retrieve and return the resource.
return Ok(new { Id = id, Name = "Sample Resource" });
}
}
```
### Summary
By following these steps, you can implement resource-based authorization in your ASP.NET Core application using the `IAuthorizationHandler` interface. This allows you to define custom logic for checking if a user has permission to access specific resources based on their claims or other criteria.
Enhanced response (with ZPI)
To implement resource-based authorization using `IAuthorizationHandler`, we need to create a custom handler that checks if the user has permission to access a specific resource. We'll also use dependency injection (DI) for registration and configure token validation parameters.
Here's a complete implementation:
1. **Create Custom Authorization Requirement:**
This class will represent the requirement for accessing a specific resource.
2. **Create Custom Authorization Handler:**
This class will handle the authorization logic based on the custom requirement.
3. **Register Services in DI:**
Register the custom handler and any other required services using scoped registration.
4. **Configure Token Validation Parameters:**
Bind token validation parameters to an options object.
### Implementation
#### 1. Custom Authorization Requirement
```csharp
public class ResourceAccessRequirement : IAuthorizationRequirement
{
public string Resource { get; }
public ResourceAccessRequirement(string resource)
{
Resource = resource;
}
}
```
#### 2. Custom Authorization Handler
```csharp
using Microsoft.AspNetCore.Authorization;
public class ResourceAccessHandler : AuthorizationHandler<ResourceAccessRequirement>
{
private readonly IAuthorizationService _authorizationService;
public ResourceAccessHandler(IAuthorizationService authorizationService)
{
_authorizationService = authorizationService;
}
protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, ResourceAccessRequirement requirement)
{
var user = context.User;
if (user == null)
{
context.Fail();
return;
}
// Simulate checking resource access
bool hasPermission = await CheckResourceAccess(user, requirement.Resource);
if (hasPermission)
{
context.Succeed(requirement);
}
}
private async Task<bool> CheckResourceAccess(ClaimsPrincipal user, string resource)
{
// Implement your logic to check if the user has permission to access the resource
// For example, you can query a database or use claims in the token
return user.HasClaim(c => c.Type == "resource_access" && c.Value == resource);
}
}
```
#### 3. Register Services in DI
```csharp
using Microsoft.Extensions.DependencyInjection;
public static class AuthorizationServiceExtensions
{
public static IServiceCollection AddResourceBasedAuthorization(this IServiceCollection services)
{
services.AddScoped<IAuthorizationHandler, ResourceAccessHandler>();
services.AddAuthorization(options =>
{
options.AddPolicy("AccessResource", policy => policy.Requirements.Add(new ResourceAccessRequirement("example_resource")));
});
return services;
}
}
```
#### 4. Configure Token Validation Parameters
```csharp
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
public static class JwtBearerServiceExtensions
{
public static IServiceCollection AddJwtBearerWithResourceValidation(this IServiceCollection services, Action<JwtBearerOptions> configureOptions)
{
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(configureOptions);
return services;
}
}
```
### Explanation
1. **Custom Authorization Requirement:**
- `ResourceAccessRequirement` is a simple class that holds the resource name required for access.
2. **Custom Authorization Handler:**
- `ResourceAccessHandler` implements `AuthorizationHandler<ResourceAccessRequirement>`.
- It checks if the user has permission to access the specified resource using the `CheckResourceAccess` method.
- The `CheckResourceAccess` method is a placeholder where you can implement your actual logic, such as querying a database or checking claims in the token.
3. **Register Services in DI:**
- `AddResourceBasedAuthorization` registers the custom handler and adds an authorization policy that requires the `ResourceAccessRequirement`.
4. **Configure Token Validation Parameters:**
- `AddJwtBearerWithResourceValidation` configures JWT Bearer authentication with options to customize token validation parameters.
This implementation provides a basic framework for resource-based authorization using `IAuthorizationHandler`. You can extend and customize it further based on your specific requirements.
Grader chain
Each grader reads the same baseline + enhanced pair and casts an independent verdict. Disagreement is the framework's own signal — not noise to be averaged away.
V1samba/Meta-Llama-3.3-70B-Instruct
BetterV4qwen2.5-coder-3b-instruct
BetterV5openrouter/qwen/qwen3-235b-a22b-2507
BetterV7qwen2.5-coder-7b-instruct
BetterV8openai/gpt-4.1
BetterV9anthropic/claude-opus-4-7
SameV12openai/gpt-4o
BetterComments
Our grader said what it said. What do you say? Comment as a guest below.
No comments yet. Be the first to say what you make of this round.