2010-08-11 50 views
2

目前我有一項服務使用UserNamePasswordValidator來驗證客戶端用戶。驗證代碼如下:WCF UserNamePasswordValidator是否需要檢查PrimaryIdentity.IsAuthenticated?

public override void Validate(String userName, String password) 
    { 
     if (userName == null) || (password == null) 
      throw new FaultException("Username and/or password not specified."); 
     if (userName != "test") && (password != "tset") 
      throw new FaultException("Invalid username and/or password."); 
    } 

正如您所看到的,當出現錯誤時,代碼將始終引發異常。

現在的問題 - 是否有任何理由我應該檢查ServiceSecurityContext.Current.PrimaryIdentity.IsAuthenticated是否在我的OperationContract函數中是否屬實?例如,

public interface IMyService 
    { 
     [OperationContract] 
     void myOpContract(); 
    } 

    public class MyService : IMyService 
    { 
     public void myOpContract() 
     { 
      // Do I really need this conditional statement? 
      if (ServiceSecurityContext.Current.PrimaryIdentity.IsAuthenticated) 
       // Proceed as expected 
      else 
       // Fail? 
     } 
    } 

任何幫助將不勝感激。

回答

1

從本文中的幾條評論 - Silverlight 3: Securing your WCF service with a custom username/password authentication mechanism和各種測試 - if ([...]PrimaryIdentity.IsAuthenticated)部分不是必需的。拋出UserNamePasswordValidator內部的錯誤會中止安全協商。

但是,代表作者的一個絕妙想法是,如果將來添加了新的綁定(連接類型)而沒有安全性,則將if ([...]PrimaryIdentity.IsAuthenticated)條件語句保留就位有幫助。