Search code examples
c#asp.net-mvcauthenticationasp.net-identitystaging

mvc5 global authentication check


I am trying to secure my staging site (mvc5 app) and am currently doing the following:

    public class HomeController : Controller
    {
    public ActionResult Index()
    {
        if (Request.IsAuthenticated){
            return View();
        }
        return RedirectToAction("Login", "Account"); 
    }

The above is far too laborious to be correct, I am certain that I shouldn't have to wrap all of my Views individually with an authentication check, however I can't seem to add a check in one location?


Solution

  • You should use Authorize action filter:

    [Authorize]
    public ActionResult Index()
    {
        return RedirectToAction("Login", "Account"); 
    }
    

    You can also use it on controller level to make sure all action methods require authentication:

    [Authorize]
    public class HomeController : Controller
    {
        //many action methods
    }
    

    If you want to use authentication for every action method in the application, you can add it as a global filter in FilterConfig.cs:

    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new AuthorizeAttribute());
    }
    

    If you do this, you have to use AllowAnonymous filter on login actions so the user can authenticate themselves.