Search code examples
asp.net-mvc-3razoractionlink

override ActionLink Behavior , and parameters to process link appearance according to user privileges (asp.net mvc3)


I want to process user privileges (edit , read,new) in my website , I am thinking about passing additional parameter byte MyRoles which has user privileges code i.e.: 0-read only , 1 - full control , 2-edit and read

So how I can override Html.ActionLink razor method to work with that , and is my method the best way to process this issue (User privileges) ?


Solution

  • and is my method the best way to process this issue (User privileges) ?

    No, passing roles as parameters to your actions would represent a security flaw as the user could pass any role he likes.

    The correct way to do this is to use the Role provider. You associate roles to your users and then define in which role the user need to be in order to access a particular action.

    For example:

    [Authorize(Roles = "Readers")]
    public ActionResult SomeAction() 
    {
        // only users belonging to the readers role will be able to access this action
    }
    

    Once you have properly secured the server side you could conditionally show/hide anchors and stuff in your Razor views:

    @if (User.IsInRole("Readers"))
    {
        @Html.ActionLink("read the news", "SomeAction")
    }
    

    And to avoid writing those ifs you could write a custom HTML helper:

    @Html.RoleActionLink("read the news", "Some Action", "Readers")
    

    The default Membership and Role providers use the default aspnetdb but you could of course extend or write custom ones in order to query your own data.