我必須在C#中爲特定用戶檢查LDAP Active Directory的用戶組。意思是我將這個用戶名傳遞給一個方法,它返回該用戶所屬的組的列表。你能幫我嗎?我搜索很多但每次都會得到新的錯誤。爲特定用戶的用戶組查詢LDAP
LDAP路徑:192.168.1.4
域名:阿爾斯蘭
用戶名:ArslanP
密碼:testad
我必須在C#中爲特定用戶檢查LDAP Active Directory的用戶組。意思是我將這個用戶名傳遞給一個方法,它返回該用戶所屬的組的列表。你能幫我嗎?我搜索很多但每次都會得到新的錯誤。爲特定用戶的用戶組查詢LDAP
LDAP路徑:192.168.1.4
域名:阿爾斯蘭
用戶名:ArslanP
密碼:testad
既然你在.NET 3.5及以上,你應該看看System.DirectoryServices.AccountManagement
(S.DS.AM)命名空間。在這裏閱讀全部內容:
Managing Directory Security Principals in the .NET Framework 3.5
基本上,引用添加到組裝System.DirectoryServices.AccountManagement
,然後你可以定義域範圍內,並可以輕鬆地查找用戶和/或組AD:
using System.DirectoryServices.AccountManagement;
public List<GroupPrincipal> GetGroupsForUser(string username)
{
List<GroupPrincipal> result = new List<GroupPrincipal>();
// set up domain context - if you do a lot of requests, you might
// want to create that outside the method and pass it in as a parameter
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
// find user by name
UserPrincipal user = UserPrincipal.FindByIdentity(username);
// get the user's groups
if(user != null)
{
foreach(GroupPrincipal gp in user.GetAuthorizationGroups())
{
result.Add(gp);
}
}
return result;
}
新的S.DS.AM使它可以很容易地與AD中的用戶和羣組一起玩:
此相關的問題可以幫助你:
Get List of Users From Active Directory In A Given AD Group
它要求th一個反向問題,當你知道該組時,如何獲得用戶列表,但其他答案也可能對你有用。
又見這個問題的答案:
發佈代碼給你帶來問題,也許我們可以幫助它。 – SGarratt 2011-03-19 16:17:46