I had to do something similar for a client, but couldn't find a way to restrict access to the site from the Azure portal itself. I went with the IP address restriction option, but did it through code in the application itself. My application was already using forms authentication, so I could perform the IP address check in the sign in action.
In your case I would suggest a custom action filter. Perform the check in the filter and if the IP address is not allowed, return a http 401 (unauthorised) status code.
Create an app setting called AllowedIpAddresses
or some such, in which you can add a comma separated list of allowed IP addresses. When you perform the check, you can set your site to allow all traffic if AllowedIpAddresses
is empty or doesn't exist. That way, you can ignore this setting in production and all traffic will be allowed by default. You can set up custom app settings for each site within the Azure portal.
Here's what a custom filter might look like. I haven't tested this!
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);
}
}