2009-07-31 98 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); 
相关问题