Reputation: 3574
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).
Upvotes: 1
Views: 2688
Reputation: 5307
If you Web service is hosted in IIS you can restrict IP addresses there:
Upvotes: 0
Reputation: 378
Since I don't think there is an automatic way to do it in WCF, you have two main options:
Otherwise, you can implement an IP filter as in the article you mentionned (i.e. 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;
}
Upvotes: 1