问题
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