如何限制网站仅从经过身份验证的IP地址打开

时间:2018-03-16 05:26:46

标签: c# asp.net .net vb.net saas

我正在开发基于SAAS的应用程序,我面临一个与之相关的问题 要求,我的应用程序应该只从经过身份验证的系统打开,并且应该基于IP地址。我将从我的数据库中授予哪个IP地址经过身份验证的许可。它会相应地工作..我没有尝试任何代码,因为我对此没有任何想法。

1 个答案:

答案 0 :(得分:1)

您可以使用实现IAuthorizationFilter接口的属性执行此操作。这将在对每个请求进行授权检查期间调用。

例如:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class IPFilterAttribute : Attribute, IAuthorizationFilter
{
    /// <summary>Invoked during authization checks for page load</summary>
    /// <param name="filterContext">Context of call, contains request and so on</param>
    public virtual void OnAuthorization(AuthorizationContext filterContext)
    {
        var request = filterContext?.HttpContext?.Request;
        if (request == null)
            throw new ArgumentNullException(nameof(filterContext));

        if (!CheckIPAddress(request.UserHostAddress))
            // Setting the Result property on filterContext stops processing.
            filterContext.Result = new HttpUnauthorizedResult("Address Forbidden");
    }

    /// <summary>Check if the supplied IP address is authorized to access this page</summary>
    /// <param name="addr">Client address to test</param>
    /// <returns>True if address is authorized, else false</returns>
    private bool CheckIPAddress(string addr)
    {
        // sample, just check if it's the localhost address
        return (addr == "127.0.0.1" || addr == "::1");
    }
}

这将检查客户端地址是否为localhost(127.0.0.1::1)并允许它通过,阻止其他所有内容。根据需要进行调整。

OnAuthorization方法中,设置filterContext.Result将停止进一步处理。在这种情况下,我使用它来显示403 - Forbidden响应。您还可以使用RedirectResult或其他一些结果对象。

您可以将其附加到特定方法或控制器类:

// Put this here to apply to all pages in this controller
[IPFilter]
public class TestController : Controller
{
    // Or here to only affect the index page
    [IPFilter]
    public ActionResult Index()
    {
        return View();
    }
}