ibubi
ibubi

Reputation: 2549

How to limit wcf service method for a specific ip

Here is my wcf service method:

[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/CheckID/{id}")]
    public string CheckID(string id)
    {
             /*Check reuqest where it comes from */
    }

I want my method send response OK if it comes/is invoked from http://particularIP.com, unless response Bad request.

How can i do that?

Upvotes: 1

Views: 944

Answers (1)

Anand Systematix
Anand Systematix

Reputation: 632

You can use IP Filter in web.config file, like :-

<serviceBehaviors>
    <behavior name="ServiceBehaviour">
      <serviceMetadata httpGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="true" />
    </behavior>
    <behavior name="RestrictedServiceBehaviour">
      <serviceMetadata httpGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="true" />
      <IPFilter filter="172.*.*.* 127.0.0.1" />          
    </behavior>
  </serviceBehaviors>

Edited

Or use can ServiceAuthorizationManager.CheckAccessCore in which you get client IP from OperationContext.

https://msdn.microsoft.com/en-us/library/system.servicemodel.serviceauthorizationmanager.checkaccesscore.aspx

Edit 2

using System.ServiceModel;
using System.ServiceModel.Channels;

OperationContext context = OperationContext.Current;
MessageProperties prop = context.IncomingMessageProperties;
RemoteEndpointMessageProperty endpoint =
    prop[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
string ip = endpoint.Address;

Upvotes: 5

Related Questions