Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a route accessible only from localhost?

I have a route like this:

[Route("api/elasticsearch/resync/products")]
[HttpGet]
public async Task<string> ResyncProducts()
{
}

How can I make it accessible only from the localhost?

like image 710
Tadej Avatar asked Mar 16 '18 13:03

Tadej


2 Answers

You can use action filter and check if request goes from loopback interface:

public class RestrictToLocalhostAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        var remoteIp = context.HttpContext.Connection.RemoteIpAddress;
        if (!IPAddress.IsLoopback(remoteIp)) {
            context.Result = new UnauthorizedResult();
            return;
        }
        base.OnActionExecuting(context);
    }
}

Then just decorate action with this attribute:

[Route("api/elasticsearch/resync/products")]
[HttpGet]
[RestrictToLocalhost]
public async Task<string> ResyncProducts()
{
}

Be careful with context.HttpContext.Connection.RemoteIpAddress. If you in forward-proxy mode (some other webserver like IIS or Nginx forwards requests to you) - this ip might always be localhost (because it's actually nginx\iis who makes a request to you), or even null, even for remote requests, if you configure your application incorrectly. But if all is configured correctly - that should be fine.

Don't use CORS like other answer suggests. It will not prevent anyone from calling your api from whatever ip. CORS is browser feature, outside of browser (and malicious user will of course not request your api via browser page) - it has exactly zero effect.

like image 147
Evk Avatar answered Oct 19 '22 11:10

Evk


Look into using CORS. Once installed correctly, you should be able to apply an attribute like so [EnableCors(origins: "http://localhost", headers: "*", methods: "*")]

See here: https://tahirnaushad.com/2017/09/09/cors-in-asp-net-core-2-0/

like image 38
Brandon Miller Avatar answered Oct 19 '22 10:10

Brandon Miller