Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using action parameters in custom Authorization Attribute in ASP.NET MVC3

Tags:

I have a controller which should only request authorization when loaded with specific parameters. Like when the parameter ID is 8 for example.

I came up with using a custom validation attribute like this:

public class MyAuthorizeAttribute : AuthorizeAttribute {     protected override bool AuthorizeCore(HttpContextBase httpContext)     {         if (/* Action's inputparameter ID = 8 */)         {         return base.AuthorizeCore(httpContext);         }         return true;     } } 

My action looks like this (not that it is interesting)

[MyAuthorize] public ActionResult Protected(int id) {     /* custom logic for setting the viewmodel from the id parameter */     return View(viewmodel); } 

The problem is as you can see that I don't know how to check for that ID parameter in the authorize attribute. Can you help me with a solution?

like image 865
vinczemarton Avatar asked Apr 05 '11 08:04

vinczemarton


People also ask

How does the Authorize attribute work?

If a user is not authenticated, or doesn't have the required user name and role, then the Authorize attribute prevents access to the method and redirects the user to the login URL. When both Roles and Users are set, the effect is combined and only users with that name and in that role are authorized.


1 Answers

If the id is passed as request parameter (GET or POST) or as a route data parameter:

protected override bool AuthorizeCore(HttpContextBase httpContext) {     // first look at routedata then at request parameter:     var id = (httpContext.Request.RequestContext.RouteData.Values["id"] as string)               ??              (httpContext.Request["id"] as string);     if (id == "8")     {         return base.AuthorizeCore(httpContext);     }     return true; } 
like image 133
Darin Dimitrov Avatar answered Sep 28 '22 19:09

Darin Dimitrov