我正在嘗試確定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。 –