简体   繁体   中英

Enable or disable certain IPs from accessing my WCF service

I'm looking for a way to enable or disable certain IPs from accessing and adding my WCF service as service reference.

Currently it's possible to add our Webservice publicly, how can I add an IP filter? Or is there any other setting I could use?

I've seen Can I setup an IP filter for a WCF Service? about adding <IPFilter /> to web.config , but the essential part in code is missing thus unusable.

Note; The webservices are part of a bigger project and cannot be separated as individual project which is available via HTTPS (a website).

Since I don't think there is an automatic way to do it in WCF, you have two main options:

  1. If you want something secured, don't want to implement anything but your environment uses firewalls, you can configure the firewall in order to refuse the connections coming from specific IP addresses.
  2. Otherwise, you can implement an IP filter as in the article you mentionned (ie as a serviceBeharvior, not described here) or simpler as a single private method called by all your public webservice methods that throw an error code if the IP of the client is not allowed (based on white or black lists of IPs in a file or a database).

     /// <summary> /// Get the client IP address. /// </summary> private string GetClientIpAddress() { string result = string.Empty; try { OperationContext context = OperationContext.Current; MessageProperties messageProperties = context.IncomingMessageProperties; RemoteEndpointMessageProperty endpointProperty = messageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; result = endpointProperty.Address; } catch (Exception ex) { logger.Error(ex); } return result; } /// <summary> /// Returns <code>true</code> if the current IP address is allowed /// to access the webservice method, <code>false</code> otherwise. /// </summary> private bool CheckIPAccessRestriction() { bool result = false; List<string> allowed = GetAllowedIpAddressesList(); if (allowed.Count() == 0) { result = true; } else { var ip = GetClientIpAddress(); result = allowed.Contains(ip); } return result; } 

If you Web service is hosted in IIS you can restrict IP addresses there:

在此处输入图片说明

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