Si vous utilisez .NET 3.5 ou une version ultérieure, vous pouvez utiliser la nouvelle fonction System.DirectoryServices.AccountManagement
(S.DS.AM), ce qui rend les choses beaucoup plus faciles qu'auparavant.
Lisez tout à ce sujet ici : Gérer les principes de sécurité de l'annuaire dans le .NET Framework 3.5
Mise à jour : Les anciens articles du magazine MSDN ne sont malheureusement plus en ligne. télécharger le CHM du magazine MSDN de janvier 2008 de Microsoft et lisez l'article qui s'y trouve.
Fondamentalement, vous devez avoir un "contexte principal" (typiquement votre domaine), un principal utilisateur, et ensuite vous obtenez ses groupes très facilement :
public List<GroupPrincipal> GetGroups(string userName)
{
List<GroupPrincipal> result = new List<GroupPrincipal>();
// establish domain context
PrincipalContext yourDomain = new PrincipalContext(ContextType.Domain);
// find your user
UserPrincipal user = UserPrincipal.FindByIdentity(yourDomain, userName);
// if found - grab its groups
if(user != null)
{
PrincipalSearchResult<Principal> groups = user.GetAuthorizationGroups();
// iterate over all groups
foreach(Principal p in groups)
{
// make sure to add only group principals
if(p is GroupPrincipal)
{
result.Add((GroupPrincipal)p);
}
}
}
return result;
}
et c'est tout ce qu'il y a ! Vous avez maintenant un résultat (une liste) des groupes d'autorisation auxquels l'utilisateur appartient - itérez sur eux, imprimez leurs noms ou tout ce dont vous avez besoin.
Mise à jour : Afin d'accéder à certaines propriétés, qui ne sont pas en surface sur le site de l UserPrincipal
vous devez creuser dans l'objet sous-jacent DirectoryEntry
:
public string GetDepartment(Principal principal)
{
string result = string.Empty;
DirectoryEntry de = (principal.GetUnderlyingObject() as DirectoryEntry);
if (de != null)
{
if (de.Properties.Contains("department"))
{
result = de.Properties["department"][0].ToString();
}
}
return result;
}
Mise à jour n°2 : Il ne devrait pas être trop difficile d'assembler ces deux bouts de code.... mais ok - c'est parti :
public string GetDepartment(string username)
{
string result = string.Empty;
// if you do repeated domain access, you might want to do this *once* outside this method,
// and pass it in as a second parameter!
PrincipalContext yourDomain = new PrincipalContext(ContextType.Domain);
// find the user
UserPrincipal user = UserPrincipal.FindByIdentity(yourDomain, username);
// if user is found
if(user != null)
{
// get DirectoryEntry underlying it
DirectoryEntry de = (user.GetUnderlyingObject() as DirectoryEntry);
if (de != null)
{
if (de.Properties.Contains("department"))
{
result = de.Properties["department"][0].ToString();
}
}
}
return result;
}