Home > database >  ASP.NET CORE API route authotization Policy should allow policy1 OR policy2
ASP.NET CORE API route authotization Policy should allow policy1 OR policy2

Time:04-18

I Have two diffrent authorize that are valid to acess a specfic api route

[Authorize(Policy = "Clients")]

OR

[Authorize(Policy = "NewBusiness")]

My path returns a list of clients like so

    // GET api/clients
    [HttpGet]
    [Authorize(Policy = "Clients")]
    [Authorize(Policy = "NewBusiness")]
    public async Task<IEnumerable<ClientViewModel>> GetAsync(bool isDeleted)
    {
        //Returns list of clients
    }

However to access this route I need the Clients policy AND the NewBusiness policy is there. This is not what I want I want the policy Clients to be valid OR the policy NewBusiness. Who can I achieve this result?

Here is the startup.cs file code where I created the policy with the claims.

    services.AddAuthorization(options =>
    {
        options.AddPolicy("Clients", policy => policy.RequireClaim("CustomerFileAccess"));
        options.AddPolicy("NewBusiness", policy => policy.RequireClaim("NewBusinessAccess"));

    });

CodePudding user response:

Maybe you should have just one policy

[Authorize(Policy = "ClientsOrNewBusiness")]

and tweak your code into something like that

services.AddAuthorization(options =>
{
    options.AddPolicy("ClientsOrNewBusiness", policy =>
        policy.RequireAssertion(context =>
            context.User.HasClaim(c => 
                c.Type == "Clients" || c.Type == "NewBusiness"
            )
        )
    ));
}

Further reading

https://docs.microsoft.com/en-us/aspnet/core/security/authorization/policies?view=aspnetcore-2.1#why-would-i-want-multiple-handlers-for-a-requirement

  • Related