I have an ASP.NET MVC website that makes use of WebAPI, SignalR.
I wish for my server (the same server that hosts the website) to make HTTP requests to a WebAPI cont
I wanted to clarify as to whether HttpRequest.Context.Request.IsLocal
is secure or not.
I just decomplied IsLocal()
from HttpWorkerRequest
and it reveals the following code:
internal bool IsLocal()
{
string remoteAddress = this.GetRemoteAddress();
if (string.IsNullOrEmpty(remoteAddress))
{
return false;
}
if (remoteAddress == "127.0.0.1" || remoteAddress == "::1")
{
return true;
}
if (remoteAddress == this.GetLocalAddress())
{
return true;
}
return false;
}
The first two checks look fine, but I was suspicious and wanted to check to see what this.GetLocalAddress()
returns to check against.
In the instance of System.Web.Hosting.IIS7WorkerRequest
, this decompiles to the following:
public override string GetLocalAddress()
{
return this.GetServerVariable("LOCAL_ADDR");
}
In my local environment this returns 127.0.0.1, so all looks good!
Also, according to this post, localhost can't be spoofed.
If you ONLY wanted to accept requests that originated from the same machine, you could check the IsLocal
property of the request context MSDN.
HttpRequest.Context.Request.IsLocal
You could then build it into a custom authorize attribute and register it globally, enforcing the requirement on all of your Web API controllers.
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Other Web API configuration code goes here
// This is a globally registered attribute
config.Filters.Add(new LocalRequestOnlyAttribute());
}
}
public class LocalRequestOnlyAttribute : AuthorizeAttribute
{
protected override bool IsAuthorized(HttpActionContext context)
{
return context.RequestContext.IsLocal;
}
}