简体   繁体   中英

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?

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM