How To Secure Your Entire MVC Application With Authorize Attribute

Scenario

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

Below are the simple solutions to overcome the above situation.

Solution 1

You can add the “Authorize” attribute in the Filter Config file to apply it to every controller.

 

  1. using System.Web.Mvc;  
  2. namespace Csharpcorner {  
  3.     public class FilterConfig {  
  4.         public static void RegisterGlobalFilters(GlobalFilterCollection filters) {  
  5.             filters.Add(new HandleErrorAttribute());  
  6.             filters.Add(new AuthorizeAttribute());  
  7.             //OR  
  8.             filters.Add(new AuthorizeAttribute {  
  9.                 Roles = "Admin"  
  10.             });  
  11.             //OR  
  12.             filters.Add(new AuthorizeAttribute {  
  13.                 Users = "ABC,XYZ"  
  14.             });  
  15.         }  
  16.     }  

 Solution 2

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

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

 

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