Question

I wonder what is the best practise for checking actually logged user's rightsfor in MVC appliaction. I would like to do this on the views and on the controllers.

Actually I can check if actual logged user is in the role like that:

User.IsInRole("roleName");

I have table with rights. Every right contain name and Enum right representation. What I want to accomplish is extension method for IPrincipal or IIdentity so I could check rights of the user like that:

Example extension method:

    public static class MyPrincipal
    {
       public static string HasRight(this IPrincipal principal, EnumRight right)
       {
           // THIS would be place where I would check if a user have right with specific enum.
           return true/false;
       }
    }

and then on the view or controller I could use this like that:

if(User.HasRight(EnumRight.AddDocuments) )
{
    //DO SOMETHING
}
  1. Is it good practise or how can I do similar mechanism simpler? Maybe independent static class not extension?

  2. How can i get actual user Id in my extension method to get from database any data which is needed to check if user has rights?

Was it helpful?

Solution

Normally, you would implement an authorization filter, and apply it to your action method. Here is the link how you can implement action filters.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top