DEV Community

loading...

Custom role based authorization in asp.net mvc

whataluckyguy profile image Lalit Kumar ・2 min read

In this post I am going to explain the logic that I use to implement roles and permissions with ASP.NET MVC, for this, I have created 4 tables.

Database

  • User: this table manages all the users of our system, and has a field called Rol_id, which refers to the following table.
  • Role: it manages the roles that our systems will implement, eg: Super Administrator, Administrator, Moderator, Super User, etc.
  • Permission: this table handles all the permissions that our business requires, eg: Can you create a new student? Can you view a student? Can you add a note to a student?
  • PermissionDeniedByRol: this table works the other way around since the normal thing would be to assign permissions to a user, for me, a user has permission for everything, so it is easier to add the permissions to which they cannot implement. I do this because it is easier, otherwise, we would have to add all the available permissions and remove them.

MOdel Layer

In this layer what I have done is create a class called FrontUser, this class allows us to know which user is authenticated in our system and also implements a method to know if they have permission or not.

public class FrontUser
{
     public static bool HasPermission (RolesPermisos value)
     {
         var user = FrontUser.Get ();
         return! user.Rol.Permission.Where (x => x.PermissionID == value)
                            .Any ();
     }

     public static User Get ()
     {
         return new User (). Get (SessionHelper.GetUser ());
     }
}
Enter fullscreen mode Exit fullscreen mode

If you noticed, the HasPermission method does the reverse, if it is true it returns false, otherwise true. In addition, it receives an Enum as a parameter. WhyRead more

Discussion

pic
Editor guide