无法获取访问该网站的用户的用户名和角色

时间:2015-07-17 09:31:20

标签: c# asp.net

我正在尝试获取当前正在访问Web应用程序的用户的名称和角色,但我编写的代码将获取服务器用户名。

请您查看我编写的以下代码并告知解决此问题的方法。

string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
string[] stringSeparators = new string[] { "\\" };
string[] uname = userName.Split(stringSeparators, StringSplitOptions.None);
userName = uname[1];
List<string> userRoles = new List<string>();
userRoles = getUserRole(userName);

public List<string> getUserRole(string userName)
{
    List<string> userNestedMembership = new List<string>();  

    DirectoryEntry domainConnection = new DirectoryEntry(); // Use this to query the default domain

    DirectorySearcher samSearcher = new DirectorySearcher();  

    samSearcher.SearchRoot = domainConnection;  
    samSearcher.Filter = "(samAccountName=" + userName + ")";  
    samSearcher.PropertiesToLoad.Add("displayName");  

    SearchResult samResult = samSearcher.FindOne();

    if (samResult != null)
    {
        DirectoryEntry theUser = samResult.GetDirectoryEntry();
        theUser.RefreshCache(new string[] { "tokenGroups" });

        foreach (byte[] resultBytes in theUser.Properties["tokenGroups"])
        {
            System.Security.Principal.SecurityIdentifier mySID = new System.Security.Principal.SecurityIdentifier(resultBytes, 0);

            DirectorySearcher sidSearcher = new DirectorySearcher();

            sidSearcher.SearchRoot = domainConnection;
            sidSearcher.Filter = "(objectSid=" + mySID.Value + ")";
            sidSearcher.PropertiesToLoad.Add("distinguishedName");

            SearchResult sidResult = sidSearcher.FindOne();

            if (sidResult != null)
            {
                string role = (string)sidResult.Properties["distinguishedName"][0];
                role = role.Substring(3, role.Length - 3);
                string[] roles = role.Split(',');
                userNestedMembership.Add(roles[0]);

            }
        }
    }
}

我没有对网络配置进行任何更改。

2 个答案:

答案 0 :(得分:1)

 userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

那就是获取wndows用户名,这可能是apppool名称。

您是否设置了thr web config和IIS以了解您要使用Windows身份验证?

(或者,如果不是,请尝试使用HTTP上下文

HttpContext.Current.User.Identity.Name

希望这会有所帮助,或者至少让你指引正确的方向

答案 1 :(得分:1)

问题可能不在于代码,而在于环境配置。要使System.Security.Principal.WindowsIdentity.GetCurrent().Name正常工作,需要满足特定要求,因为它使用户在服务器端。 Here is nice post描述了如何使IIS在用户帐户下工作(使用Windows身份验证)。

相关问题