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

1

6

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");
            });
Ce answered 17/12, 2020 at 14:53 Comment(2)
learn.microsoft.com/en-us/aspnet/core/security/authorization/… Halfway downish under Why would I want multiple handlers for a requirement?Novation
Ah ok that makes sense! I didn't understand how it all fit together when I tried to read it before :) Thanks @TonyHopkinsonCe
C
10

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"))));
            });
Ce answered 17/12, 2020 at 15:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.