UserPrincipal.FindByIdentity returns 多个

UserPrincipal.FindByIdentity returns multiple

我需要使用 Active Directory 验证用户并检查他们的组。问题是用户返回多个 UserPrincipal。管理员无法找到此用户的问题。我的代码很简单;

var usr = UserPrincipal.FindByIdentity(context, username);

现在我知道我可以做到了;

var usr = new WindowsPrincipal(WindowsIdentity.GetCurrent());
if (usr.IsInRole("MyRole")
{
   //Do stuff
}

这对当前登录的用户有效,但是,有时我需要对当前未登录的用户进行身份验证

我有一个系统可以监控最近的帐户锁定,使用:

UserPrincipal.FindByLockoutTime(...)

我用它来给我一个最近被锁定的帐户列表。 我可以单击用户名以使用以下方式深入了解详细信息:

UserPrincipal.FindByIdentity(context, userId)

我可以看到我有一个名为 Administrator 的帐户,每次单击它向下钻取时,我都会收到相同的错误:

MultipleMatchesException

我发现 FindByIdentity 方法接受一个 int 类型的重载:

https://docs.microsoft.com/en-us/dotnet/api/system.directoryservices.accountmanagement.identitytype?view=netframework-4.8

据我所知,我正在通过 SamAccountName 将方法签名更改为:

进行查询
UserPrincipal.FindByIdentity(context, 0, userId)

为我解决了这个问题。