Get Organization / Departament and Organization / Title with UserPrincipal - AD and C #

2

I'm using the System.DirectoryServices.AccountManagement reference and I have the following code:

string dnsAD = "USINA.REDE";
string groupName = "Grupo Controle Acesso Gestao de Ativos"; //seta o grupo de acesso
PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, dnsAD);
GroupPrincipal groupPrincipal = GroupPrincipal.FindByIdentity(principalContext, groupName);
if (principalContext.ValidateCredentials(Login, Senha))
{
    UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(principalContext, Login);
    if (!(userPrincipal == null) && (userPrincipal.IsMemberOf(groupPrincipal))) //verifica se user é membro do grupo

I would like if within this context, using UserPrincipal, I can get Organization information such as Departament and Title?

Thanks in advance!

    
asked by anonymous 02.07.2014 / 18:28

1 answer

2

You can use the UserPrincipal class together with a class named DirectoryEntry to access some properties of the master. This class represents a node or object in the Active Directory hierarchy. The class UserPrincipal inherits from a class Principal which in turn is associated with a DirectoryEntry .

To get the DirectoryEntry over of a Principal we use the GetUnderlyingObject method of this class. It turns out that every DirectoryEntry object has a collection called Properties that has the ADDS properties for that active directory object. This property is of type PropertyCollection and has a Contains method to check if a property is specified for that AD entry.

Basically this is done like this:

directoryEntry.Properties.Contains("propriedade");

This is a bool that says whether the property is there or not. If the property is you can access its value with array syntax and accessing the Value property:

directoryEntry.Properties["propriedade"].Value.ToString();

With this idea, the best you can do is create extension methods to make everything more flexible. Create an extension method for the Principal class that returns a property of the over DirectoryEntry like this:

public static string GetProperty(this Principal principal, string propriedade)
{
    DirectoryEntry directoryEntrySobrejacente = principal.GetUnderlyingObject() as DirectoryEntry;

    if (directoryEntrySobrejacente.Properties.Contains(propriedade))
    {
        return directoryEntrySobrejacente.Properties[propriedade].Value.ToString();
    }
    else
    {
        return string.Empty;
    }
}

Then create extension methods for the specific properties you want. For example, a GetDepartment method to return the department property by passing the property name to string.

I do not know much about AD so I do not know if this approach works exactly for your problem. Try it there and say it worked out.

References

02.07.2014 / 18:33