Search code examples
asp.net-mvcasp.net-mvc-5rolesclaims-based-identityclaims

Role or claim based authorization? Or hybrid?


I have a ASP.NET MVC project and customer requires a separate access for different roles. He wants to have many roles, but some of them have very similar access (except only some things). Of course, I can make it like the following:

if (User.IsInRole("Superadmin") || User.IsInRole("CompanyAdmin") || ...)
{
   // bla-bla-bla
}
else if (....)
{
}

However, it seems to me that it is not as flexible as it should be. Any small variations in rights require the script to review the whole project and change it.

I think to make a "hybrid" approach, i.e. set a role for a user as now, and also set claims. And thus check afterwards only the claims, but not list of the roles. If it is needed to change the access for any role, then just add/remove a claim in one place after login (not even necessary to save it to DB).

What do you think?


Solution

  • Use Claims for everything. Some Claims can simply be - roles. So, you can have a user with Claim: role > CompanyAdmin but same user can also have Claim: canAccessSuperadminDashboard > true (or whatever way you want to defined additional rights).

    When you combine the two you get very granular approach where your first checks can be for role Claims and then for more granular things you check particular Claims.

    One of the benefits of this approach is that your role claims get mapped to Principal user so your Authorize(Roles="Admin") work directly with role Claims.