ASP.NET MVC 5: Secure your web app

Securing your MVC app is one of the tricky things when migrating, as an engineer, from classic ASP.NET to ASP.NET MVC.

By default, access is allowed to every controller and action of your web app, which is potentially unsafe. As an architect, I am sure you would like to enforce the security of your app and don’t rely on whether a developer will actually remember to add the [Authorize] attribute to a sensitive controller or action.

Well, you can use global filters to enforce that!
Open App_Start folder, double click on FilterConfig.cs and add as a global filter the AuthorizeAttribute() like this:

using System.Web;
using System.Web.Mvc;

namespace MyNewProject {
    public class FilterConfig {
        public static void RegisterGlobalFilters( GlobalFilterCollection filters ) {
            filters.Add( new HandleErrorAttribute() );
            filters.Add( new AuthorizeAttribute() );
        }
    }
}

This way, every controller and action needs authorization before access. Of course you will need to allow access to all action your app will (like login) need like this:

[AllowAnonymous]
public ActionResult Login() {
    return View();
}
Advertisements

One thought on “ASP.NET MVC 5: Secure your web app

  1. Pingback: MVC: Custom AuthorizeAttribute for custom authentication | My CodePad

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