Scenario: If you would like to secure your admin pages, you would add “Authorize” attribute for all your admin controllers. However, you might get a situation like; you need to secure your entire MVC application without using any login page. For vast applications, it would be difficult to add “Authorize” attribute for each controller and manage it.

Below are the simple solutions to overcome above situation.

Solution 1: You can add “Authorize” attribute in the filter Config file to apply it to every controller.

using System.Web.Mvc;

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



            filters.Add(new AuthorizeAttribute());
            
            //OR

            filters.Add(new AuthorizeAttribute { Roles = "Admin" });

            //OR

            filters.Add(new AuthorizeAttribute { Users  = "ABC,XYZ" });

        }

    }
}

 

Solution 2: You can create one base class (AuthorizeController in our example), which should inherit Controller Class. Now, instead of inheriting from Controller, all of your controllers should inherit this new class (i.e., AuthorizeController class).

[Authorize]
public abstract class AuthorizeController : Controller
{
    //your methods here(If any).
}
public class MyController : AuthorizeController
{
   //Your Action Methods here.
}

 

Note: If you would like to provide access on any controller or action method to user, add “AllowAnonymous” attribute specific to that controller or action method.

 

Happy Coding 🙂