Question

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?

Was it helpful?

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.

OTHER TIPS

Use the Authorize attribute AuthorizeAttribute:

public class HomeController : Controller
{
    [Authorize]
    public ActionResult Index()
    {
        return View();
    }
}

If the request is unauthenticated, MVC will redirect the user to the login route (defined in web.config authentication section).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top