Adding .NET Core authorization policy based on conditions

906 Views Asked by At

I'm looking for a way to add an authorization policy based on a condition.

I have two policies added.

//Policy 1
 options.AddPolicy("MyPolicy1",
 policy =>
 {
   policy.RequireClaim("aud");
   policy.RequireClaim("aud", "internal");
   policy.Requirements.Add(new CustomInternalRequirement());
 });

//Policy 2
 options.AddPolicy("MyPolicy2",
 policy =>
 {
   policy.RequireClaim("aud");
   policy.RequireClaim("aud", "external");
   policy.RequireAuthnticatedUser();
   policy.Requirements.Add(new CustomExternalRequirement());
 });

In my controller, I want to use the above policies based on the audience. If the audience is "internal" then I want to use "MyPolicy1" and if the audience is "external" then I want to use "MyPolicy2".

This is my controller.

//MyController
[HttpGet]
[Authorize(Policy = "MyPolicy1")] // OR // [Authorize(Policy = "MyPolicy2")]
public virtual async Task<IActionResult> GetMyData()
{
//
}

Any idea how can I achieve this?

I tried to implement a "Combined" policy with RequireAssertion so that I can use the policy "Combined" in the controller. But it seems not working. Maybe I missed something or implemented it wrong.

   options.AddPolicy("Combined",
   policy =>
   {
   policy.RequireClaim("aud");
   
   policy.RequireAssertion(context =>
   {
       if(context.User.HasClaim(c=>c.Type=="aud" && c.Value == "internal")
       {
          policy.Requirements.Add(new CustomInternalRequirement());
       }
       else
       {
          policy.RequireAuthnticatedUser();
          policy.Requirements.Add(new CustomExternalRequirement());
       }
       return context.HasSucceeded;
   });
 });
0

There are 0 best solutions below