0

What is the best way of implementing a mechanism where the system check the user role before permitting it to access some specific page? Also to enable maybe some link/action in the page, for example for users that have 'Super' role, they might be able to delete/edit the data while the rest can only see it?

For your information, I do not use the out of the box User management from the ASP.NET MVC (where the user is created in the .mdf database embedded to webapp), but I have developed my own user module (for authenticating, registering and deleting user).

So ..what is the best practice for this problem?

Haikal Nashuha
  • 2,958
  • 7
  • 44
  • 67

1 Answers1

2

You would write a custom ValidationAttribute: http://msdn.microsoft.com/en-AU/library/system.componentmodel.dataannotations.validationattribute.aspx

Basically, you inherit from ValidationAttribute, and override IsValid():

public class IsAnAdminAttribute : ValidationAttribute {
    protected override bool IsValid(object obj) {
        if (Membership.UserInRole("admin"))
            return true; // they can access it
        else
            return false; // can't access it
    }
}

..then you apply it to controller actions:

[HttpGet]
[IsAnAdmin]
public ActionResult MyAction() {
    // only administrators can access this now
}
Simon Whitehead
  • 63,300
  • 9
  • 114
  • 138
  • Supposed that I have two roles `admin` and `normal` and a controller method `MonitorTraffic`. How can I filter so that only `admin` can have the access to this page in this controller method? Sorry kind of new to MVC4 myself. From the example given, I failed to see how the annotation can do that. Maybe could you please show me an example? – Haikal Nashuha Jul 08 '13 at 04:24
  • I've updated my answer. The attribute is fired by MVC because it inherits from `ValidationAttribute`. It will call the `IsValid` method and if `IsValid` returns `true`, access will be granted. If it returns `false`, access will be denied. – Simon Whitehead Jul 08 '13 at 04:40
  • Understood. But where can I create this class? I mean proper place to put it? Not in model i guess? Sorry, newbie question again – Haikal Nashuha Jul 08 '13 at 04:44
  • No worries. They are a front-end solution.. so I would put them in a "Code" folder in the UI project (your MVC project). – Simon Whitehead Jul 08 '13 at 04:48