2012-11-01 109 views
0

我已經用幾個簡單的函數構建了一個Restful WCF服務。提出了一項新的要求。如何限制訪問WCF restful功能到特定的IP範圍?

其中一個功能應該只能訪問特定的ip範圍。

什麼是最好的實施方式?我認爲一個簡單的方法是簡單地配置IIS的規則,將阻止IP範圍根據請求模式 - 找不到這樣的選項。 奧弗

+0

使用IIS 7,你應該能夠做到這一點。 http://technet.microsoft.com/en-us/library/cc730889.aspx – marcellscarlett

回答

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);