【发布时间】:2018-03-16 05:26:46
【问题描述】:
我正在开发基于 SAAS 的应用程序,但我遇到了一个与以下相关的问题 要求,我的应用程序应该只能从经过身份验证的系统打开,并且应该基于 IP 地址。我会从我的数据库中授予对哪个 IP 地址进行身份验证的许可。它会相应地工作..我没有尝试任何代码,因为我对此一无所知。
【问题讨论】:
标签: c# asp.net .net vb.net saas
我正在开发基于 SAAS 的应用程序,但我遇到了一个与以下相关的问题 要求,我的应用程序应该只能从经过身份验证的系统打开,并且应该基于 IP 地址。我会从我的数据库中授予对哪个 IP 地址进行身份验证的许可。它会相应地工作..我没有尝试任何代码,因为我对此一无所知。
【问题讨论】:
标签: c# asp.net .net vb.net saas
您可以使用实现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();
}
}
【讨论】: