gpt4 book ai didi

c# - 返回用户所属的所有 Active Directory 应用程序组的列表

转载 作者:可可西里 更新时间:2023-11-01 11:21:03 24 4
gpt4 key购买 nike

我想列出用户所属的所有 Active Directory 应用程序组。但我一无所获。

感谢您的建议。

public List<string> GetGroups(string strUserName)
{
DirectoryEntry objADAM = default(DirectoryEntry);
// Binding object.
DirectoryEntry objGroupEntry = default(DirectoryEntry);
// Group Results.
DirectorySearcher objSearchADAM = default(DirectorySearcher);
// Search object.
SearchResultCollection objSearchResults = default(SearchResultCollection);
// Results collection.
string strPath = null;
// Binding path.
List<string> result = new List<string>();
// Construct the binding string.
strPath = "LDAP://CHCAD.abc/DC=abc";
//Change to your ADserver
// Get the AD LDS object.
try
{
objADAM = new DirectoryEntry(strPath);
objADAM.RefreshCache();
}
catch (Exception e)
{
throw e;
}
// Get search object, specify filter and scope,
// perform search.
try
{
objSearchADAM = new DirectorySearcher(objADAM);
objSearchADAM.Filter = "(&(objectClass=group)(samaccountname=" + strUserName + "))";
objSearchADAM.SearchScope = SearchScope.Subtree;
objSearchResults = objSearchADAM.FindAll();
}
catch (Exception e)
{
throw e;
}
// Enumerate groups
try
{
if (objSearchResults.Count != 0)
{
foreach (SearchResult objResult in objSearchResults)
{
objGroupEntry = objResult.GetDirectoryEntry();
result.Add(objGroupEntry.Name);
}
}
else
{
throw new Exception("No groups found");
}
}
catch (Exception e)
{
throw new Exception(e.Message);
}
return result;
}

最佳答案

如果您使用的是 .NET 3.5 及更高版本,则应查看 System.DirectoryServices.AccountManagement (S.DS.AM) 命名空间。在这里阅读所有相关信息:

基本上,您可以定义域上下文并在 AD 中轻松找到用户和/或组:

// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

// find a user - this will search for DN and samAccountName and display name and a few more
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, strUserName);

if(user != null)
{
// if user is found - get the groups that user belongs to
PrincipalSearchResult<Principal> authGroups = user.GetAuthorizationGroups();

List<string> groupNames = new List<string>();

foreach(Principal group in authGroups)
{
// do something with the groups - like add their name to a List<string>
groupNames.Add(group.Name);
}
}

新的 S.DS.AM 使得在 AD 中与用户和组一起玩真的很容易!

PS:否则,如果您无法切换到 S.DS.AM,您应该查看 my answer to another StackOverflow question处理同样的问题。基本上只需检查 DirectoryEntry 对象的 memberOf 属性。

关于c# - 返回用户所属的所有 Active Directory 应用程序组的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10727436/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com