【问题标题】:how to restrict access to WCF restful function to specific IP range?如何将 WCF RESTful 功能的访问限制在特定 IP 范围内?
【发布时间】:2012-11-01 09:32:32
【问题描述】:

我已经构建了一个带有几个简单功能的 Restful WCF 服务。提出了新的要求。

其中一个功能应该只能在特定的 IP 范围内访问。

实现这一点的最佳方法是什么?我认为一个简单的方法是简单地配置 IIS 与将根据请求模式阻止 ip 范围的规则 - 找不到这样的选项..

谢谢! 提供

【问题讨论】:

标签: c# wcf rest iis-7


【解决方案1】:

您是否尝试过实现IParameterInspector?您的代码可能如下所示:

public class IPFilterAttribute : Attribute, IOperationBehavior, IParameterInspector
{
    private string _rangeFrom;
    private string _rangeTo;

    public IPFilterAttribute(string rangeFrom, string rangeTo)
    {
        _rangeFrom = rangeFrom;
        _rangeTo = rangeTo;
    }

    public void ApplyDispatchBehavior(
        OperationDescription operationDescription,
        DispatchOperation dispatchOperation)
    {
        dispatchOperation.ParameterInspectors.Add(this);
    }

    public void AfterCall(string operationName, object[] outputs,
                          object returnValue, object correlationState)
    {
    }

    public object BeforeCall(string operationName, object[] inputs)
    {
        RemoteEndpointMessageProperty clientEndpoint =
            OperationContext.Current.IncomingMessageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
        if (!IsClientInInRange(clientEndpoint.Address))
        {
            throw new SecurityException(string.Format("Calling method '{0}' is not allowed from address '{1}'.", operationName, clientEndpoint.Address));
        }

        return null;
    }

    private bool IsClientInRange(string clientAddress)
    {
        // do the magic to check if client address is in the givn range
    }

    public void AddBindingParameters(OperationDescription operationDescription, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
    {
    }

    public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)
    {
    }

    public void Validate(OperationDescription operationDescription)
    {
    }
}

那么你所要做的就是用这个属性来装饰web方法:

    [OperationContract]
    [WebInvoke(...)]
    [IPFilter("64.18.0.0", "64.18.15.255")]
    string GetData(string value);

【讨论】:

    【解决方案2】:

    几个选项: - 您可以使用防火墙为您完成这项工作

    • IIS 具有可以阻止 ip 的功能,但您必须在 IIS 中托管您的服务。

    • 您可以使用 WCF 获取客户端地址,然后接受/拒绝呼叫。

    参考: http://www.danrigsby.com/blog/index.php/2008/05/21/get-the-clients-address-in-wcf/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-20
      • 1970-01-01
      • 2011-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-17
      相关资源
      最近更新 更多