我知道在控制器顶部的MVC中,您可以使用[Authorize()]
属性将对整个控制器的访问限制为某些经过身份验证的用户和/或角色,但不能通过IP限制,但必须在每个控制器实例。有没有办法将对整个MVC区域的访问限制为经过身份验证的用户/角色或请求源IP?
答案 0 :(得分:16)
在您所在地区创建一个基本控制器:
[AuthorizeArea(AllowIpAddresses = new [] {"1.1.1.1", "1.2.3.4"})]
public class CustomAreaBaseController : Controller
{
public CustomAreaBaseController()
{
// possibly any other common code that you want to run for all controllers in this area
}
}
您所在地区的所有控制器都来自基础控制器:
public class HomeController : CustomAreaBaseController
{
// actions for this controller
}
创建自定义授权属性:
public class AuthorizeArea : AuthorizeAttribute
{
public string[] AllowIpAddresses { get; set; }
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
bool isValid = false;
if (httpContext == null)
throw new ArgumentNullException("httpContext");
// get current ip address
var ipAddress = httpContext.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(ipAddress))
ipAddress = httpContext.Request.ServerVariables["remote_host"];
if (AllowIpAddresses.Contains(ipAddress)) isValid = true;
return base.AuthorizeCore(httpContext) && isValid;
}
}