获取当前用户的SID的最佳方法是什么?

时间:2009-07-31 18:10:14

标签: c# .net asp.net

先决条件详情

  1. 使用.NET 2.0。
  2. 代码位于可以从ASP.Net,Windows窗体或控制台应用程序调用的公共库中。
  3. 在公司网络上的Windows域中运行。
  4. 问题

    获取当前用户的SID的最佳方法是什么?我不是在谈论正在执行应用程序的身份,而是正在访问界面的用户。在后台应用程序和基于桌面的应用程序中,这应该是实际执行应用程序的标识,但在ASP.Net(没有版本化)中,这应该是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 个答案:

答案 0 :(得分:4)

我认为没有更好的方法来获取这些信息 - 你必须以某种方式获得WindowsPrincipal和.NET相当干净的API摘要,这些信息在User对象后面。我只是把它放在一个很好的方法中并用一种方法包裹起来并称之为一天。

嗯,好吧,你应该做的一件事(除非你的网络用户总是将成为WindowsIdentity),这将是检查空身份并根据你的任何规则处理它有

答案 1 :(得分:1)

WindowsIdentity类是“为您完成的内置类”。只要你有一个有效的WindowsIdentity可以使用,你就可以得到一个简单的解决方案。

或者,如果您有相关用户的用户名并且想要直接从AD获取SID,则可以构建自己的库以使用DirectoryServices命名空间并为您的用户检索DirectoryEntry(这是相当复杂的作为DirectoryServices的过程很棘手)。如果您有需要,甚至可以使用LDAP来获取它。

答案 2 :(得分:1)

不使用第三方库如果用户更改了用户名,此代码将提供正确的结果。

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);