2009-07-31 125 views
14

前提條件詳細獲取當前用戶的SID的最佳方式是什麼?

  1. 工作在.NET 2.0。
  2. 該代碼位於可從ASP.Net,Windows窗體或控制檯應用程序中調用的公用庫中。
  3. 在公司網絡上的Windows域中運行。

問題

什麼是獲取當前用戶的SID的最佳方式?我不是在談論執行應用程序的身份,而是在訪問該接口的用戶。在後臺應用程序和基於桌面的應用程序中,這應該是實際執行應用程序的身份,但在ASP.Net中(沒有impersionation),應該是HttpContext.Current.User SID。

當前方法

這是我有現在。它看起來......錯了。這很討厭。有沒有更好的方法來做到這一點,還是有一些內置的課程可以幫助你?

public static SecurityIdentifier SID 
{ 
    get 
    { 
     WindowsIdentity identity = null; 

     if (HttpContext.Current == null) 
     { 
      identity = WindowsIdentity.GetCurrent(); 
     } 
     else 
     { 
      identity = HttpContext.Current.User.Identity as WindowsIdentity; 
     } 

     return identity.User; 
    } 
} 

回答

3

我不認爲這是在這個信息得到一個更好的辦法 - ......你拿到WindowsPrincipal得到某種方式和.NET的,而乾淨的API抽象的用戶對象後面。我只是留下這個不錯的東西,用一種方法包裝起來,並稱之爲一天。

好了,好了,有一件事你應該做的(除非你的網絡用戶總是將是的WindowsIdentity),這將是檢查null身份,並根據的任何規則你必須處理它。

+1

用戶將總是有一個身份(如果他們不那麼它是一個更大的問題)。感謝你的回答。 – 2009-07-31 18:18:24

1

WindowsIdentity類是「爲你做的內置類」。只要你有一個有效的WindowsIdentity可以使用,你就可以得到一個簡單的解決方案。

或者,如果您有用戶名,並且想要直接從AD獲取SID,則可以構建自己的庫以使用DirectoryServices命名空間併爲您的用戶檢索DirectoryEntry(這是相當公平的由於DirectoryServices的複雜過程非常棘手)。如果您有需要,您甚至可以使用LDAP來獲取它。

0

不使用第三方庫如果用戶更改了他的用戶名,此代碼將給出正確的結果。

String SID = ""; 
string currentUserName = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString(); 

RegistryKey regDir = Registry.LocalMachine; 

      using (RegistryKey regKey = regDir.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI\SessionData", true)) 
      { 
       if (regKey != null) 
       { 
        string[] valueNames = regKey.GetSubKeyNames(); 
        for (int i = 0; i < valueNames.Length; i++) 
        { 
         using (RegistryKey key = regKey.OpenSubKey(valueNames[i], true)) 
         { 
          string[] names = key.GetValueNames(); 
          for (int e = 0; e < names.Length; e++) 
          { 
           if (names[e] == "LoggedOnSAMUser") 
           { 
            if (key.GetValue(names[e]).ToString() == currentUserName) 
             SID = key.GetValue("LoggedOnUserSID").ToString(); 
           } 
          } 
         } 
        } 
       } 
      }MessageBox.Show(SID); 
相關問題