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

本文关键字:用户 角色 网站 获取 访问 | 更新日期: 2023-09-27 18:03:16

我试图获得当前正在访问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]);
            }
        }
    }
}

我没有做任何更改web配置

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

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

显示的是windows用户名,很可能是appool的名称。

你设置了web配置和IIS知道你想要使用windows认证吗?

(如果没有,请尝试使用HTTP上下文

)
HttpContext.Current.User.Identity.Name

希望这对你有所帮助,或者至少给你一个正确的方向

问题可能不在于代码,而在于环境配置。要使System.Security.Principal.WindowsIdentity.GetCurrent().Name按照您想要的方式工作,需要满足一些特定的要求,因为它在服务器端获得了用户。这是一个很好的帖子,描述了如何使IIS在用户帐户下工作(使用Windows身份验证)。