Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp .net mvc authorization

What is the best way to protect certain areas of your web application in asp .net mvc. I know we can put [Authorization] attribute at each action, but this seems very tedious since you have to put it all over the place. I'm using membership provider and trying the way I used to do in postback model by setting this protection based on the folder. I use web.config <location> section to protect some folders. I tried this in mvc, it seems to be working, but most of tutorial uses the [Authorization] way.

Which one is the better method?

like image 625
dritterweg Avatar asked Dec 06 '22 05:12

dritterweg


2 Answers

I'd highly recommend against putting it in the web.config. Actually, so do Conery, Hanselman, Haack, and Guthrie -- though not highly (p223 of Professional ASP.NET MVC 1.0)

Routes are subject to change, especially in MVC. With the WebForm model, routes are physically represented on the file system so you didn't really have to worry about it. In MVC, routes are "dynamic" for lack of a better term.

You could end up with multiple routes mapping to one controller causing a maintenance pain in the web.config. Worse, you could inadvertently have a route invoke a controller accidentally or forget to update the web.config after adding/modifying routes and leave yourself open.

If, however, you secure your controller instead of the actual route, then you don't need to worry about keeping the web.config in sync with the goings-on of the controllers and changing routes.

Just my 2 cents.

like image 147
andymeadows Avatar answered Dec 26 '22 20:12

andymeadows


One possible solution is to create a "protected controller" and use it as a base class for all the areas of your application that you want to protect

[Authorize]
public class ProtectedBaseController : Controller { 

}

public class AdminController : ProtectedBaseController { 
  ...
}

public class Admin2Controller : ProtectedBaseController { 
  ...
}
like image 42
Marco Staffoli Avatar answered Dec 26 '22 20:12

Marco Staffoli