[英]Possible to [Authorize] at the Area level in ASP.NET MVC 2?
Slapping on [Authorize]
attributes on Controllers and Actions to restrict access is awesome. 对控制器和动作上的
[Authorize]
属性进行拍打以限制访问非常棒。
Is it possible to do the equivalent for an entire Area in MVC 2? 是否可以在MVC 2中为整个区域执行等效操作? Where I can restrict Area-wide access dependent on Roles/Users/whatever in a central place instead of littering them throughout all the Controllers?
我可以限制区域范围内的访问权限取决于角色/用户/中心位置的任何内容,而不是在所有控制器中乱丢它们?
您可以使用由此属性修饰的基本控制器,该区域中的所有控制器都派生自该控制器。
For MVC 3 and above: 对于MVC 3及以上版本:
I just started on this... but so far this is working pretty good for me. 我刚刚开始这个......但到目前为止,这对我来说非常有用。
I create a custom AuthorizeAttribute class and add this in the RegisterGlobalFilters function. 我创建了一个自定义AuthorizeAttribute类,并将其添加到RegisterGlobalFilters函数中。
In CustomAuthorizeAttribute I check for various conditions based on the area it is in. 在CustomAuthorizeAttribute中,我根据它所在的区域检查各种条件。
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new CustomAuthorizeAttribute());
filters.Add(new HandleErrorAttribute());
}
}
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var routeData = httpContext.Request.RequestContext.RouteData;
var controller = routeData.GetRequiredString("controller");
var action = routeData.GetRequiredString("action");
var area = routeData.DataTokens["area"];
var user = httpContext.User;
if (area != null && area.ToString() == "Customer")
{
if (!user.Identity.IsAuthenticated)
return false;
}
else if (area != null && area.ToString() == "Admin")
{
if (!user.Identity.IsAuthenticated)
return false;
if (!user.IsInRole("Admin"))
return false;
}
return true;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.