8

コントローラーの上部にあるMVCでは、[Authorize()]属性を使用して、そのコントローラー全体へのアクセスを特定の認証されたユーザーおよび/またはロールに制限できますが、IPでは制限できませんが、これはコントローラーインスタンスごとに行う必要があります。MVC エリア全体へのアクセスを、認証されたユーザー/ロールに、またはリクエストのソース IP によって制限する方法はありますか?

4

1 に答える 1

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
}

カスタム Authorize 属性を作成します。

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;
    }
}
于 2013-08-05T18:03:21.663 に答える