将 User.Identity.Name.Substring 与 Active 目录上的用户名进行比较将返回误导性结果

本文关键字:用户 比较 结果 误导性 返回 Name Identity User Substring Active | 更新日期: 2023-09-27 18:37:23

我编写了以下方法来存储用户名以用于日志目的:-

if (ModelState.IsValid)
                {
string ADusername = User.Identity.Name.Substring(User.Identity.Name.IndexOf("''") + 1);
repository.InsertOrUpdateTechnologyAssociation(ua, ADusername);
repository.Save();
//code hoes here
                }

以上会将管理员的用户名存储为"管理员"全部小写。而如果我从活动目录中检索用户名,如下所示:-

public List<DomainContext> GetADUsers(string term=null)
        {
            List<DomainContext> results = new List<DomainContext>();
            using (var context = new PrincipalContext(ContextType.Domain, "WIN-SPDEV"))
            using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
            {
                var searchResults = searcher.FindAll();

                foreach (Principal p in searchResults)
                {
                   if (term == null || p.SamAccountName.ToString().ToUpper().StartsWith(term.ToUpper()))
                   {
                    DomainContext dc = new DomainContext();
                    dc.DisplayName = p.DisplayName;
                    dc.UserPrincipalName = p.UserPrincipalName;
                    dc.Name = p.Name;
                    dc.SamAccountName = p.SamAccountName ;
                    dc.DistinguishedName =     p.DistinguishedName;
                    results.Add(dc);
                }
                }
            }
            return results;
        }

然后,Name & SamAccountName 将是"管理员",乞讨时大写 A。因此,这在我的应用程序内部引起了问题,因为当我尝试将登录用户与活动目录上的用户名进行比较时,结果总是错误的,因为管理员 != 管理员。因此,为了解决这个问题,我通过将两个值更改为小写然后比较它们来编写我的比较:-

bool isadminByuser =  tms.SecurityRoles.Where(a => a.Name == "Administrator").SingleOrDefault().SecurityRoleUsers.Any(a => a.UserName.ToLower() == user.ToLower());

那么这样的比较是否会导致将来出现问题,或者将 suername 更改为小写是安全的。?或者管理员和管理员可以代表两个不同的用户?谢谢

将 User.Identity.Name.Substring 与 Active 目录上的用户名进行比较将返回误导性结果

Active Directory 用户名不区分大小写。所以基本上Administratoradministrator代表完全相同的帐户。