How require authorization within whole ASP .NET MVC application

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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.

Method 2

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" });
    }
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x