ofer
ofer

Reputation: 4476

how to restrict access to WCF restful function to specific IP range?

I've built a Restful WCF service with few simple functions. a new requirememt has been raised.

one of the functions should be accessible only to a specific ip range.

what is the best way to implement this? I thought that an easy way is to simply configure the IIS with a rule that will block ip range according the request pattern - cant find such option..

Thanks! ofer

Upvotes: 0

Views: 2381

Answers (2)

dmusial
dmusial

Reputation: 1564

Have you tried implementing IParameterInspector? Your code could look something like this:

public class IPFilterAttribute : Attribute, IOperationBehavior, IParameterInspector
{
    private string _rangeFrom;
    private string _rangeTo;

    public IPFilterAttribute(string rangeFrom, string rangeTo)
    {
        _rangeFrom = rangeFrom;
        _rangeTo = rangeTo;
    }

    public void ApplyDispatchBehavior(
        OperationDescription operationDescription,
        DispatchOperation dispatchOperation)
    {
        dispatchOperation.ParameterInspectors.Add(this);
    }

    public void AfterCall(string operationName, object[] outputs,
                          object returnValue, object correlationState)
    {
    }

    public object BeforeCall(string operationName, object[] inputs)
    {
        RemoteEndpointMessageProperty clientEndpoint =
            OperationContext.Current.IncomingMessageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
        if (!IsClientInInRange(clientEndpoint.Address))
        {
            throw new SecurityException(string.Format("Calling method '{0}' is not allowed from address '{1}'.", operationName, clientEndpoint.Address));
        }

        return null;
    }

    private bool IsClientInRange(string clientAddress)
    {
        // do the magic to check if client address is in the givn range
    }

    public void AddBindingParameters(OperationDescription operationDescription, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
    {
    }

    public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)
    {
    }

    public void Validate(OperationDescription operationDescription)
    {
    }
}

Then all you have to do is decorate the web method with this attribute:

    [OperationContract]
    [WebInvoke(...)]
    [IPFilter("64.18.0.0", "64.18.15.255")]
    string GetData(string value);

Upvotes: 1

Vasanthan
Vasanthan

Reputation: 310

couple options: - you can use a firewall to do this job for you

  • IIS has capabilities that can block ip, but you will have to host your service in IIS.

  • you can use WCF to get the client address and then accept/deny the call.

Refer: http://www.danrigsby.com/blog/index.php/2008/05/21/get-the-clients-address-in-wcf/

Upvotes: 0

Related Questions