2012-02-14 64 views
0

我想驗證一個WCF Rest web服務,但我不確定如何去解決它。它看起來像許多其他問題與.net 3.5 WCF(如WebServiceHost2)中的東西有關,這些東西似乎不再存在。WCF REST驗證行爲

我想這樣做基於消息的身份驗證的WCF服務與自定義用戶名和密碼。然而

<behaviors> 
    <serviceBehaviors> 
    <behavior name="PasswordValidator"> 
     <serviceCredentials> 
     <userNameAuthentication userNamePasswordValidationMode="Custom" 
           customUserNamePasswordValidatorType="MyNamespace.PasswordValidator, MyNamespace"/> 
     </serviceCredentials> 
    </behavior> 
    </serviceBehaviors> 
</behaviors> 

,因爲我使用REST我不能得到這個基礎的web.config配置行爲會:從我可以告訴,這可以通過定期WCF下面來完成。我不知何故需要在我的serviceRoute中做到這一點。

RouteTable.Routes.Add(new ServiceRoute("", new WebServiceHostFactory(), typeof(HelloService))); 

有沒有人知道如何做到這一點,或有任何關於休息和WCF 4.0的消息基於安全的好教程?

+1

基於信息安全是SOAP構建周圍的WS-Security。你只是想要對自己的證書商店進行認證? – 2012-02-15 08:56:35

+1

以下鏈接可能會有幫助:http://stackoverflow.com/questions/6021612/wcf-restful-web-services-and-custom-authentication – Rajesh 2012-02-15 09:58:45

+0

http://www.leastprivilege.com/TokenBasedAuthenticationForWCFHTTPRESTServicesAuthentication.aspx – Rajesh 2012-02-15 10:00:43

回答

0

我解決這個問題的方法是實現一個自定義授權屬性,該屬性查看我添加到HTTP標頭集合中的兩個自定義字段。

這似乎是工作得很好。

public class UserAndPasswordAuthenticationAttribute : Attribute, IOperationBehavior, IParameterInspector 
    { 
     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) 
     { 
      string username = WebOperationContext.Current 
            .IncomingRequest.Headers["username"]; 
      string password = WebOperationContext.Current 
            .IncomingRequest.Headers["password"]; 


      if (username != "bob" || password!= "123") 
      { 
       WebOperationContext.Current.OutgoingResponse.StatusCode = 
        HttpStatusCode.Unauthorized; 
       throw new UnauthorizedAccessException(""); 
      } 

      return null; 
     } 

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

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

     public void Validate(OperationDescription operationDescription) 
     { 
     } 
    } 

然後我可以只是在我的合同中添加該屬性的方法,以確保他們