我正在尝试确定AD中的用户帐户是否已启用。为此,我使用下面的代码:为什么UserPrincipal.Enabled返回不同的值?
string domain = "my domain";
string group = "my security group";
string ou = "my OU";
//init context
using (var cnt= new PrincipalContext(ContextType.Domain, domain))
{
//find the necessary security group
using (GroupPrincipal mainGroup
= GroupPrincipal.FindByIdentity(cnt, IdentityType.Guid, group))
{
if (mainGroup != null)
{
//get the group's members
foreach (var user in mainGroup.GetMembers()
.OfType<UserPrincipal>()
.Where(u => u.DistinguishedName.Contains(ou)))
{
//ensure that all the info about the account is loaded
//by using FindByIdentity as opposed to GetMembers
var tmpUser= UserPrincipal.FindByIdentity(cnt,
user.SamAccountName);
//actually I could use `user` variable,
//as it gave the same result as `tmpUser`.
//print the account info
Console.WriteLine(tmpUser.Name + "\t" +
tmpUser.Enabled.HasValue + "\t" +
tmpUser.Enabled.Value);
}
}
}
}
问题是,当我下的管理帐户运行这段代码,我得到了真正的结果,而当我在一个非priviledged帐户运行它,user.Enabled
回报false
对于一些帐户,它应该是true
。
唯一相似q &一个我设法找到有
- UserPrincipal.Enabled returns False for accounts that are in fact enabled?
- Everything in Active Directory via C#.NET 3.5 (Using System.DirectoryServices.AccountManagement)
不帮助这里。
这是为什么?我可以选择在非特权帐户下获取此信息吗?
下面是另一种方法:How to determine if user account is enabled or disabled:
private bool IsActive(DirectoryEntry de)
{
if (de.NativeGuid == null)
return false;
int flags = (int)de.Properties["userAccountControl"].Value;
if (!Convert.ToBoolean(flags & 0x0002))
return true;
else
return false;
}
相同的方法在Active Directory Objects and C#进行说明。
但是,当在无特权用户帐户下运行时,userAccountControl
属性为null
,并且无法确定帐户的状态。
这里的解决方法是使用PrincipalContext Constructor,指定具有足够权限的用户的凭证来访问AD。
它对我来说依然不清楚,为什么无特权用户完全可以访问AD,并且无法获取某些特定帐户属性的值。可能这与C#无关,应该在AD中配置...
如果你可以从你的链接添加确切的指令,你的答案会更好,更安全的链接破坏 – ForceMagic
谢谢。从链接添加相关信息的blockquote。 –