Search code examples
c#asp.netservicestackservicestack-bsd

Restrict service to internal network BUT load balancer?


In our ServiceStack (v3)-based API, we have some services that are for internal use only, so we've put a [Restrict(InternalOnly = true)] attribute on all of our internal request DTOs.

The problem is that we use load balancing, and the restricted services get publicly accessible to everyone because the IP calling the API is always the load balancer's IP, and therefore an internal IP.

Is there any way to circumvent this, so that the internal services are restricted to internal IPs EXCEPT the load balancer's IP?


Solution

  • I haven't seen a built in way (See [Restrict] tests) to restrict based on specific IPs. However you can trivially filter the requests yourself using a custom attribute:

    public class AllowLocalExcludingLBAttribute : RequestFilterAttribute
    {
        public override void Execute(IHttpRequest req, IHttpResponse res, object requestDto)
        {
            // If the request is not local or it belongs to the load balancer then throw an exception
            if(!req.IsLocal || req.RemoteIp == "10.0.0.1")
                throw new HttpError(System.Net.HttpStatusCode.Forbidden, "403", "Service can only be accessed internally");
        }
    }
    

    Then you simply add [AllowLocalExcludingLB] on your services or action methods where you would have otherwise used the [Restrict] attribute or use it in conjunction with other restrictions. Replace 10.0.0.1 with your load balancer IP.