如何从服务器获取用户的SID?

时间:2015-08-05 17:24:58

标签: c# asp.net visual-studio-2013

我有这段代码:

public bool UserCheck()
    {
        using (var context = new PrincipalContext(ContextType.Domain))
        {
            try
            {
                using (var user = UserPrincipal.FindByIdentity(context, IdentityType.Sid, WindowsIdentity.GetCurrent().User.Value))
                {
                    if (user != null) return true;
                    else return false;
                }
            }
            catch (System.Runtime.InteropServices.COMException) { return false; }
        }
    }

它将检查当前用户是否存在于服务器的AD中。

这个代码在我的机器上测试时工作正常,但是当我发布它时,代码开始返回false,经过进一步的调试,我发现了

WindowsIdentity.GetCurrent().User.Value

获取服务器的SID,而不是用户的。

如何在代码发布时获取用户的SID?

1 个答案:

答案 0 :(得分:1)

在开发计算机上运行站点时,Visual Studio会在IIS Express中加载站点。 IIS Express作为登录用户运行。这就是您在执行时看到用户名的原因:

WindowsIdentity.GetCurrent().User.Value

发布Web应用程序后,您可能正在IIS下运行它。您需要将IIS和ASP.NET配置为使用集成Windows身份验证(使用Kerberos或NTLM)

有关详细信息,请参阅this link;有关“ASP.NET和Windows身份验证”的信息,请参阅Google