C# – Should it be a claim, a role or a policy

.net coreasp.net-coreauthorizationcrazor

The distinction between roles and claims is that roles describe a set of users and claims describe a property of a user. So there can be a role "Administrator", but there can also be a claim "HasElevatedPrivilegeBadge". Both can allow the same action. Now which one should I pick if I want to allow only certain people to do certain things, for example:

CanAddItem, CanUpdateItem, CanDeleteItem,
CanAddProduct, CanUpdateProduct, CanDeleteProduct

I could create role "Administrator" and add to it claims "CanAddItem", "CanUpdateItem", etc., but "CanAddItem" doesn't describe a property of a user. It says what the user can do, which is not what a claim should do, should it?

Another approach is to create policies, such as:

policy.AddPolicy("CanAddItem", policy => {
    policy.RequireAuthenticatedUser()
          .RequireRole("Administrator");
});

But for more than 20 policies, it will take a good chunk of my Startup class. Is there any other way of doing this, or is one of these the preferred one?

I'd like to point out that I'm specifically looking for a solution for .Net Core Identity. I'm asking for a solution on how to fit my requirement into Identity tables provided by the framework.

Best Answer

Essentially you are describing a mapping of Role to Permission.

I think this is pretty much covered by the standard [Authorize(Role=xxx)] on your controller actions, where the implied permission is CanExecuteThisAction. No need for extra policies as they would simply act as a mapping, potentially confusing the issue and as you say, adding a lot of boilerplate code.

The policies seem to be aimed at more complicated permissions, where you need to execute some logic against the claims or other properties of the user, the example being the AtLeast21 policy where the users claim is a date of birth.

They would I guess replace custom AuthorizeAttribute classes.

I would not use them when the default Authorize attribute can handle it on its own, such as with role checking.

Related Topic