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

删除回忆录丶 提交于 2019-12-07 17:07:16

问题


title pretty much says it all.

I have a website which will only run behind a login so I want to ensure that nothing can be accessed unless you're logged in. This includes ActionResults, JsonResults etc...

Currently, I have [Authorize] all over my controllers which is quite tedious and not very DRY :)

So can I protect the entire website with 1 magic line of code? (The login page will obviously need to be accessible)

Also, please note that I will still need to further protect some of the Actions to only be used by certain Users/Roles


回答1:


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()
    {
        ...
    }
}



回答2:


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




回答3:


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() 
    {
        ...
    }
}


来源:https://stackoverflow.com/questions/4092803/protect-entire-website-behind-a-login-i-e-authorize-all-actions-within-all-co

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!