ASP.NET MVC security best practice -- Add Authorize attribute for controller instead of individual actions when appropriate

Recently I was going through an ASP.NET MVC web application's source and noted that in some of the Controllers all of its Actions required authorization to access them. So Authorize attribute was added to all of the actions in the controller, as shown below .

    public class AdminSettingsController : Controller
    {
        //
        // GET: /AdminSettings/

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

        //
        // GET: /AdminSettings/Details/5

        [Authorize]
        public ActionResult Details(int id)
        {
            return View();
        }

        //
        // GET: /AdminSettings/Create

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


        //
        // GET: /AdminSettings/Edit/5

        [Authorize]
        public ActionResult Edit(int id)
        {
            return View();
        }


        //
        // GET: /AdminSettings/Delete/5

        [Authorize]
        public ActionResult Delete(int id)
        {
            return View();
        }

    }

But if all of the controller's actions need authorization then you can add [Authorize] attribute to the entire Controller itself. Doing this would avoid room for errors, as you may miss to add the Authorize attribute to individual actions and that could become a security vulnerability.

Below you can see I have removed the Authorize attribute from individual actions.

    [Authorize]
    public class AdminSettingsController : Controller
    {
        //
        // GET: /AdminSettings/

        public ActionResult Index()
        {
            return View();
        }

        //
        // GET: /AdminSettings/Details/5

        public ActionResult Details(int id)
        {
            return View();
        }

        //
        // GET: /AdminSettings/Create

        public ActionResult Create()
        {
            return View();
        }


        //
        // GET: /AdminSettings/Edit/5

        public ActionResult Edit(int id)
        {
            return View();
        }


        //
        // GET: /AdminSettings/Delete/5

        public ActionResult Delete(int id)
        {
            return View();
        }

    }

Also note that, if forms authentication is configured then if you add Authorize attribute to an action or controller then MVC will redirect the user to the login page, which is great.

Bookmark / Share