28

I create application where every action beside those which enable login should be out of limits for not logged user.

Should I add [Authorize] annotation before every class' headline? Like here:

namespace WebApplication2.Controllers {
[Authorize]
    public class HomeController : Controller {




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

        public ActionResult About() {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact() {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}

or there is a shortcut for this? What if I want to change rules for one and only action in particular controller?

1

3 Answers 3

45

Simplest way is to add Authorize attribute in the filter config to apply it to every controller.

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

        //Add this line
        filters.Add(new AuthorizeAttribute());
    }
}

Another way is to have all of your controllers inheriting from a base class. This is something I do often as there is almost always some shared code that all of my controllers can use:

[Authorize]
public abstract class BaseSecuredController : Controller
{
    //Various methods can go here
}

And now instead of inheriting from Controller, all of your controllers should inherit this new class:

public class MySecureController : BaseSecuredController
{
}

Note: Don't forget to add AllowAnonymous attribute when you need it to be accessible to non-logged in users.

Sign up to request clarification or add additional context in comments.

Comments

11

To build upon DavidG's answer, if you need to require a certain role (in Windows authentication, for example, where everyone is authorized) you can do this:

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

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

Comments

0

I know the OP was tagged with just asp.net-mvc-5, but for completeness, for ASP.NET Core MVC 6, if you're building controllers with views (via builder.Services.AddControllersWithViews()), there are 2 ways you can require authorization for the whole app:

  1. Set authorization policy
    namespace DL.Poc.Identity.Server
    {
        public class Program
        {
            public static void Main(string[] args)
            {
                var builder = WebApplication.CreateBuilder(args);
    
                ...
    
                builder.Services.AddControllersWithViews();
    
                builder.Services.AddAuthorization(options =>
                {
                    options.FallbackPolicy = new AuthorizationPolicyBuilder()
                        .RequireAuthenticatedUser()
                        .Build();
                });
    
                var app = builder.Build();
    
                ...
    
                app.UseAuthorization();
    
                app.MapControllerRoute(
                    name: "areaRoute",
                    pattern: "{area:exists}/{controller=home}/{action=index}/{id?}");
    
                app.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=home}/{action=index}/{id?}");
    
                app.Run();
            }
        }
    }
    
  2. Add authorization filter
    namespace DL.Poc.Identity.Server
    {
        public class Program
        {
            public static void Main(string[] args)
            {
                var builder = WebApplication.CreateBuilder(args);
    
                ...
    
                builder.Services.AddControllersWithViews(options =>
                {
                    var policy = new AuthorizationPolicyBuilder()
                     .RequireAuthenticatedUser()
                     .Build();
    
                    options.Filters.Add(new AuthorizeFilter(policy));
                });
    
                var app = builder.Build();
    
                ...
    
                app.UseAuthorization();
    
                app.MapControllerRoute(
                    name: "areaRoute",
                    pattern: "{area:exists}/{controller=home}/{action=index}/{id?}");
    
                app.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=home}/{action=index}/{id?}");
    
                app.Run();
            }
        }
    }
    

2 Comments

Are you reffering to .NET 6 or something that was short lived few years ago and was caled ASP .NET MVC 6 before they switched to ASP .Net Core naming?
I am referring .NET 6 and ASP.NET Core MVC: learn.microsoft.com/en-us/aspnet/core/mvc/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.