Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to authorize user role at a particular mvc3 controller/action?

How can I set authorization to a particular action within a controller?

Example (authorizes valid username logged in):

    [Authorize]  
    public ActionResult ChangePassword()
    {
        return View();
    }

So, I'm looking to validate access based on the users roles...something like this:

    [Authorize]
    [AuthorizeRole="Admin"]     // This is psuedo but something like this   
    [AuthorizeRole="SuperUser"] // This is psuedo but something like this 
    public ActionResult ChangePassword()
    {
        return View();
    }

Is something like the above possible? If not what is the best way to secure access based on roles for particular controller/action security?

Thanks!

like image 918
genxgeek Avatar asked Dec 07 '22 18:12

genxgeek


2 Answers

This is what you need.

[Authorize(Roles = "Admin, SuperUser")] 

See: http://msdn.microsoft.com/en-us/library/dd460317.aspx

like image 183
Daniel A. White Avatar answered Jan 01 '23 10:01

Daniel A. White


[Authorize(Users="Jacquo, Steve", Roles="Admin, SuperUser")]

Users : Comma-separated list of usernames that are allowed to access the action method.

Roles : Comma-separated list of role names. To Access the action method, users must be in at least one of these roles.

http://msdn.microsoft.com/en-us/library/system.web.mvc.authorizeattribute.aspx

like image 41
Aleksey Cherenkov Avatar answered Jan 01 '23 09:01

Aleksey Cherenkov