Protect entire website behind a login i.e. “Authorize” all Actions within all controllers

◇◆丶佛笑我妖孽 提交于 2019-12-05 21:31:55

If you have multiple controllers, then make a AuthorizeController from which you inherit your controllers that must be protected. Just set the [Authorize] attribute to the AuthorizeController:

[Authorize]
public class AuthorizeController: Controller
{
}

public class HomeController : AuthorizeController
{
    ...
}

// don't inherit AccountController from AuthorizeController
public class AccountController : Controller
{
    public ActionResult Login()
    {
        ...
    }
}

If you are trying to secure an entire website, you could use a global filter:

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

See here for more information http://visualstudiomagazine.com/blogs/tool-tracker/2013/06/authenticating-users-in-aspnet-mvc-4.aspx

Nevermind! I think I found it!

Placing [Authorize] above the Controller class seems to protect all actions, and is further customisable on a per-action basis. YES!

[Authorize]
public class SomeController : Controller 
{
    // All logged in users
    public ActionResult Index() 
    {
        ...
    }

    [Authorize(Roles="Admin")] // Only Admins
    public ActionResult Details() 
    {
        ...
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!