Alex
Alex

Reputation: 722

How to check claim for value in API request (ASP.NET Core 2.2)

I'm using claims-based-identity in ASP.NET Core 2.2

From what I've read, it's possible to make custom claims/policy authorization using the following format (found in this answer)

[Authorize(Policy = "DataDrivenExample")]
public IActionResult GetFooBar()
{
    // Omitted for brevity...
}

However, in my application, I need to check whether the user has access to THIS specific object. For example, something like this:

[Authorize(Policy = "EditFooBar:" + id)]
public IActionResult EditFooBar(string id)
{
    // Omitted for brevity...
}

The handler then something like this...?

public class EditFooBarHandler : AuthorizationHandler<DataDrivenRequirement>
{

protected override void Handle(AuthorizationContext context, 
                               string id)
{
    var hasClaim = context.HttpContext.User.Claims.Any(c => c.Type == "EditFooBar" && c.Value == id);
    ...etc...
}

It's not really feasible to make a separate policy for every possible value of id.

Basically, how can I pass data into a policy requirement checker that is different for every request to that API endpoint?

Upvotes: 0

Views: 3225

Answers (1)

alans
alans

Reputation: 1040

I believe what you are looking for in this case is Resource-based Authorization.

https://learn.microsoft.com/en-us/aspnet/core/security/authorization/resourcebased?view=aspnetcore-2.2

Upvotes: 3

Related Questions