ASP.NET 5 Authorize against two or more policies

2019-01-23 11:59发布

问题:

Is it possible to apply authorization against two or more policies? I am using ASP.NET 5, rc1.

[Authorize(Policy = "Limited,Full")]
public class FooBarController : Controller
{
    // This code doesn't work
}

If not, how may I achieve this without using policies? There are two groups of users that may access this controller: "Full" and "Limited". Users may either belong to "Full" or "Limited", or both. They only require to belong to one of the two groups in order to access this controller.

回答1:

Not the way you want; policies are designed to be cumulative. For example if you use two separate attributes then they must both pass.

You have to evaluate OR conditions within a single policy. But you don't have to code it as ORs within a single handler. You can have a requirement which has more than one handler. If either of the handlers flag success then the requirement is fulfilled. See Step 6 in my Authorization Workshop.



回答2:

Once setting up a new policy "LimitedOrFull" (assuming they match the claim type names) create a requirement like this:

options.AddPolicy("LimitedOrFull", policy =>
    policy.RequireAssertion(context =>
        context.User.HasClaim(c =>
            (c.Type == "Limited" ||
             c.Type == "Full"))));

https://docs.microsoft.com/en-us/aspnet/core/security/authorization/policies?view=aspnetcore-2.1#using-a-func-to-fulfill-a-policy



回答3:

Net Core has an option to have multiple AuthorizationHandlers that have the same AuthorizationRequirement type. Only one of these have to succeed to pass authorization https://docs.microsoft.com/en-us/aspnet/core/security/authorization/policies?view=aspnetcore-2.1#why-would-i-want-multiple-handlers-for-a-requirement



回答4:

try to using Role instead

[Authorize(Role = "Limited,Full")]