0

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

其中一项功能应该只能由特定的 IP 范围访问。

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

谢谢!提供

4

2 回答 2

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);
于 2012-11-07T23:21:53.330 回答
0

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

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

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

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

于 2012-11-07T10:37:36.747 回答