How to secure your ASP.NET MVC 4 application in 30 seconds!

Back in the days of ASP.NET WebForms (eek!) securing your application was a piece of cake. You could readily rely on the web.config file to lock down access to every page in your app given the peace of mind that every resource was a physical file in a well known directory on the web server.

ASP.NET MVC / Web API is a completely different beast! Now you want to shift your gaze to securing your controllers , think about it – multiple URL’s can hit the same controller so mapping this out in a web.config file is painful and error prone.

Enter the super useful AuthorizeAttribute class that ships with MVC 4.0. Out of the box  all controllers and actions are accessible to all users, both authenticated and  unauthenticated. To turn this off simply apply a global filter

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());

filters.Add(new System.Web.Mvc.AuthorizeAttribute());
}

And when it comes granting anonymous access to a resource like a login page you can override this behavior with its first cousin the AllowAnonymous Attribute

public class LoginController : Controller
{
//
// GET: /login/
[AllowAnonymous]
public ActionResult Index()
{
return View();
}

that’s it folks !

may the source be with you

Aidan

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s