Justin Morrison
Justin Morrison

Reputation: 587

How can I add an OR clause to a ASP.NET CORE Authorization Policy?

I have a list of claims that are required to do certain operations in the system. I have a list of policies to verify the existence of those claims to perform certain operations. That all works as expected.

What I would like to do is ignore the checks for those claims if another claim has a certain value. For example, I have these policies:

            options.AddPolicy("AdjustmentFundAdmin", policy => { 
                policy.RequireClaim("AdjustmentFundAdmin");
            });
            options.AddPolicy("ManifestApprover", policy => {
                policy.RequireClaim("ManifestApprover");
            });
            options.AddPolicy("InvoiceProcessor", policy => {
                policy.RequireClaim("InvoiceProcessor");
            });

But what I would like to do is if there is the claim/value: policy.RequireClaim("manna_tms_userlevel", "magician") then ignore these claim checks in the policy.

I tried to add multiple but that seems to just require both instead of one or the other.

            options.AddPolicy("AdjustmentFundAdmin", policy => {
                policy.RequireClaim("AdjustmentFundAdmin");
                policy.RequireClaim("manna_tms_userlevel", "magician");
            });

Upvotes: 6

Views: 2775

Answers (1)

Justin Morrison
Justin Morrison

Reputation: 587

Thanks to @TonyHopkinson for the help!

I was able to make it work like this:

           options.AddPolicy("AdjustmentFundAdmin", policy => {
                policy.RequireAssertion(context =>
                    context.User.HasClaim(c =>
                    (c.Type == "AdjustmentFundAdmin" || 
                    (c.Type == "manna_tms_userlevel" && 
                     c.Value == "magician"))));
            });

Upvotes: 11

Related Questions