背景
我一直在使用UserPrincipal.GetAuthorizationGroups
一段时间来检查2个不同应用程序的权限。他们已经好几年了。最近一些用户已经收到标题中提到的错误(System.DirectoryServices.AccountManagement.PrincipalOperationException
)而其他用户没有。我怀疑它可能与在Windows Server 2012上运行的新域控制器有关,因为问题在添加后的第二天就开始了。完整错误如下:
例外:
System.DirectoryServices.AccountManagement.PrincipalOperationException: 枚举组时发生错误(1301)。小组的 SID无法解决。
at System.DirectoryServices.AccountManagement.SidList.TranslateSids(String target,IntPtr [] pSids) 在System.DirectoryServices.AccountManagement.SidList..ctor(SID_AND_ATTR [] sidAndAttr)
在System.DirectoryServices.AccountManagement.AuthZSet..ctor(Byte [] userSid,NetCred凭据, ContextOptions contextOptions,String flatUserAuthority,StoreCtx userStoreCtx,Object userCtxBase)
at System.DirectoryServices.AccountManagement.ADStoreCtx.GetGroupsMemberOfAZ ... p)
at System.DirectoryServices.AccountManagement.UserPrincipal.GetAuthorizationGroups
问题:
我该如何解决这个问题?
答案 0 :(得分:5)
我找到了使用DirectorySearcher
的替代方案:
var allDomains = Forest.GetCurrentForest().Domains.Cast<Domain>();
var allSearcher = allDomains.Select(domain =>
{
DirectorySearcher searcher = new DirectorySearcher(
new DirectoryEntry("LDAP://" + domain.Name));
searcher.Filter = String.Format(
"(&(&(objectCategory=person)(objectClass=user)(userPrincipalName=*{0}*)))",
"Current User Login Name");
return searcher;
}
);
var directoryEntriesFound =
allSearcher.SelectMany(searcher =>
searcher.FindAll()
.Cast<SearchResult>()
.Select(result => result.GetDirectoryEntry()));
var memberOf = directoryEntriesFound.Select(entry =>
{
using (entry)
{
return new
{
Name = entry.Name,
GroupName = ((object[])entry.Properties["MemberOf"].Value)
.Select(obj => obj.ToString())
};
}
}
);
foreach (var user in memberOf)
{
foreach (var groupName in user.GroupName)
{
if (groupName.Contains("Group to Find"))
{
// Do something if the user is in that group
}
}
}
答案 1 :(得分:0)
答案 2 :(得分:0)
我有同样的例外。如果有人不想使用&#34; LDAP&#34;,请使用此代码。因为我有嵌套组,我使用了GetMembers(true),并且它的时间比GetMembers()稍长。
或从这里下载修补程序,如@Tilo:http://support.microsoft.com/kb/2830145
public bool IsMember(UserPrincipal user, string groupName)
{
try
{
var context = new PrincipalContext(ContextType.Domain, Environment.UserDomainName);
var group = GroupPrincipal.FindByIdentity(context, groupName);
if (group == null)
{
//Not exist
}
else
{
if (group.GetMembers(true).Any(member => user.SamAccountName.ToLower() == member.SamAccountName.ToLower()))
{
return true;
}
}
}
catch (Exception exception)
{
//exception
}
return false;
}