2013-01-23 36 views
0

我目前的方法來驗證WSE的用戶名和密碼(令牌)如下:驗證令牌(WSE法)在WCF

public override void VerifyToken(SecurityToken token1) 
{ 
    if (token1 is UsernameToken) 
    { 
     string u1 = (token1 as UsernameToken).Username; 
     string p1 = (token1 as UsernameToken).Password; 

     // see if this user is already authenticated 
     UsernameToken token2 = TokenCache[u1] as UsernameToken; 
     if ((token2 != null) && token2.IsCurrent && (token2.Password == p1)) 
     { 
      // less than 30s? 
      if ((DateTime.Now - token2.Created) < TimeSpan.FromSeconds(30)) 
       return; 
      else 
       // no - remove from cache 
       RemoveFromCache(token1); 
     } 

     // not cached, so actually check 
     // NB Two or more requests for same user at about same time may all fail test above 
     // and thus all will call ValidateUser. But then they will all call CacheSecurityToken below, 
     // which is OK - the last one wins. 
     if (Membership.ValidateUser(u1, p1)) 
     { 
      Cache(token1); 
      return; 
     } 

     // not authenticated 
     throw new Exception("Authentication failed for " + u1); 
    } 

任何想法,我怎麼可以使WCF的變化?我已經使用Microsoft.Web.Service3 WSE程序集 - 不想使用它。想從我的整個解決方案中擺脫UsernameToken。

+0

您的實際要求是什麼?你需要保留相同版本的認證協議,還是可以使用最新的最新版本?許多WSE協議是臨時版本,而標準是開發的。 –

+0

@John:我的要求很簡單。我們有使用WSE(.NET 2),那麼我們就把它改成了.NET 3.5開發的Web應用程序,但我們使用相同的WSE服務。現在,我們要升級的應用程序WCF和.NET 4 基本上,我們希望爲我們所用,但想在客戶端和服務器端追逐的Web服務的邏輯來保持隧道邏輯相同。 上述方法是在驗證用戶時,他們嘗試登錄到網絡應用程序的安全層。 希望我給你足夠的信息來幫助我。 – Vinnie

回答

1

我已經管理驗證每個web服務調用我的安全憑證。我使用了Directory鍵值對來緩存憑據 - 如果有人在尋找類似的東西,這將有所幫助。

public class SecurityManager : UserNamePasswordValidator 
{ 
    //cacheCredentials stores username and password 
    static Dictionary<string, string> cacheCredentials = new Dictionary<string, string>(); 
    //cacheTimes stores username and time that username added to dictionary. 
    static Dictionary<string, DateTime> cacheTimes = new Dictionary<string, DateTime>(); 

    public override void Validate(string userName, string password) 
    { 
     if (userName == null || password == null) 
     { 
      throw new ArgumentNullException(); 
     } 
     if (cacheCredentials.ContainsKey(userName)) 
     { 
      if ((cacheCredentials[userName] == password) && ((DateTime.Now - cacheTimes[userName]) < TimeSpan.FromSeconds(30)))// && timespan < 30 sec - TODO 
       return; 

      cacheCredentials.Remove(userName); 
      cacheTimes.Remove(userName); 
     } 
     if (Membership.ValidateUser(userName, password)) 
     { 
      //cache usename(key) and password(value) 
      cacheCredentials.Add(userName, password); 
      //cache username(key), time that username added to dictionary 
      cacheTimes.Add(userName, DateTime.Now); 
      return; 
     } 
     throw new FaultException("Authentication failed for the user");  
    } 
}