Restricting WCF Service access to only localhost which is hosted using console application

564 views Asked by At

I am very new to WCF.I have a WCF service hosted using a console application but, the WCF needs to be called from a C# webservice hosted on the same machine. So how can I restrict the endpoint access to loopback ip, i.e 127.0.0.1

Right now I can access the WCF service endpoints hosted in a different machine(say 10.X.X.X) .For example I can type http://10.X.X.X/api/v1/getStatus and get the response. This url should be restricted. My requirement is only http://localhost/api/v1/getStatus should be able to fetch the response from the WCF service hosted.

2

There are 2 answers

0
Ding Peng On BEST ANSWER

In the link you gave, IPFilter is a custom node that implements the IDispatchMessageInspector interface to intercept IP. Here is my demo:

   public class ServerMessageLogger : IDispatchMessageInspector
{
    public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
    {
        return null;
    }

    public void BeforeSendReply(ref Message reply, object correlationState)
    {
        OperationContext context = OperationContext.Current;
        MessageProperties messageProperties = context.IncomingMessageProperties;
        RemoteEndpointMessageProperty endpointProperty =
          messageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
        if (endpointProperty.Address.Equals("::1"))
        {
            Console.WriteLine("OK");
        }
        else
        {
            reply = null;
        }
    }
}

We need to implement the IDispatchMessageInspector interface. When the server sends a response to the client, first determine whether the client's IP address is localhost. If it is not localhost, the server will return an empty response.

 [AttributeUsage(AttributeTargets.Interface | AttributeTargets.Class, AllowMultiple = false)]
    public class CustContractBehaviorAttribute : Attribute, IContractBehavior
    {
        public void AddBindingParameters(ContractDescription contractDescription, ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
        {
            return;
        }

        public void ApplyClientBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, ClientRuntime clientRuntime)
        {
            return;
        }

        public void ApplyDispatchBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, DispatchRuntime dispatchRuntime)
        {
            dispatchRuntime.MessageInspectors.Add(new ServerMessageLogger());
        }

        public void Validate(ContractDescription contractDescription, ServiceEndpoint endpoint)
        {
            return;
        }
    }

Then we need to add ServerMessageLogger to the behavior of the service.

enter image description here

Finally, you need to apply CustContractBehavior to the service.

5
Lukasz Nowakowski On