是的。通常我所做的是使用提供的用户名作为 sAMAccountName 进行全局目录搜索。使用 PrincipalSearcher 执行此操作需要获取底层 DirectorySearcher 并将其替换为 SearchRoot。一旦找到相应的用户对象,我就会从用户对象的路径中提取域并将其用作身份验证步骤的域。您如何进行身份验证取决于您需要它执行的操作。如果您不需要模拟,您可以使用PrincipalContext.ValidateCredentials来确保用户名/密码使用PrincipalContext匹配,该 PrincipalContext 与您之前找到的用户帐户的域相匹配。如果您需要模拟,请查看此参考。
// NOTE: implement IDisposable and dispose of this if not null when done.
private DirectoryEntry userSearchRoot = null;
private UserPrincipal FindUserInGlobalContext( string userName )
{
using (PrincipalSearcher userSearcher = new PrincipalSearcher())
{
using (PrincipalContext context
= new PrincipalContext( ContextType.Domain ))
{
userSearcher.QueryFilter = new UserPrincipal( context );
DirectorySearcher searcher
= (DirectorySearcher)userSearcher.GetUnderlyingSearcher();
// I usually set the GC path from the existing search root
// by doing some string manipulation based on our domain
// Your code would be different.
string GCPath = ...set GC path..
// lazy loading of the search root entry.
if (userSearchRoot == null)
{
userSearchRoot = new DirectoryEntry( GCPath );
}
searcher.SearchRoot = userSearchRoot;
using (PrincipalContext gcContext =
new PrincipalContext( ContextType.Domain,
null,
GCPath.Replace("GC://",""))
{
UserPrincipal userFilter = new UserPrincipal( gcContext );
userFilter.SamAccountName = userName;
userSearcher.QueryFilter = userFilter;
return userSearcher.FindOne() as UserPrincipal;
}
}
}
}