我不得不爲客戶端做類似的事情,但是找不到限制Azure門戶本身訪問站點的方法。我使用IP地址限制選項,但通過應用程序本身的代碼完成。我的應用程序已經使用表單身份驗證,所以我可以在登錄操作中執行IP地址檢查。
在你的情況我建議一個custom action filter。在過濾器中執行檢查,如果IP地址不被允許,則返回http 401(未授權)狀態碼。
創建一個名爲AllowedIpAddresses
的應用程序設置或一些這樣的,您可以在其中添加允許的IP地址的逗號分隔的列表。執行檢查時,如果AllowedIpAddresses
爲空或不存在,則可以將您的站點設置爲允許所有流量。這樣,您可以在生產中忽略此設置,並且默認情況下會允許所有流量。您可以爲Azure門戶中的每個站點設置自定義應用程序設置。
這裏有一個自定義過濾器可能是什麼樣子。我沒有測試過這個!
public class AccessRestrictionFilterAttribute : ActionFilterAttribute
{
// simple wrapper around ConfigurationManager.AppSettings for testability
private readonly IAppSettingsHandler appSettingsHandler;
public AccessRestrictionFilterAttribute(IAppSettingsHandler appSettingsHandler)
{
this.appSettingsHandler = appSettingsHandler;
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var isAllowed = false;
var userIpAddress = filterContext.HttpContext.Request.UserHostAddress;
if (appSettingsHandler.AllowedIpAddresses.Split(new[] { ',' }).Any(x => x == userIpAddress))
{
isAllowed = true;
}
if (!isAllowed)
{
filterContext.Result = new HttpUnauthorizedResult();
}
base.OnActionExecuting(filterContext);
}
}
感謝湯姆。我喜歡這種基於配置的解決方案,它允許我使用web.config轉換在測試過程中輕鬆應用此限制,但在構建生產時將其刪除。 – John 2013-04-09 17:33:51