如何通过IP /角色/用户保护整个MVC区域?

8 asp.net-mvc-areas asp.net-mvc-4 razor-2

我知道在控制器顶部的MVC中,您可以使用该[Authorize()]属性将对整个控制器的访问限制为某些经过身份验证的用户和/或角色,但不能通过IP限制,但这必须在每个控制器实例上完成.有没有办法将对整个MVC区域的访问限制为经过身份验证的用户/角色或请求源IP?

Dmi*_*try 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
    }
}
Run Code Online (Sandbox Code Playgroud)

让您所在地区的所有控制器都来自基本控制器:

public class HomeController : CustomAreaBaseController
{
    // actions for this controller
}
Run Code Online (Sandbox Code Playgroud)

创建自定义授权属性:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)