Artigos / Tekever.eu

Artigos de desenvolvimento e opinião em tecnologia.

Secções:

Linux | Windows | .NET / ASP | LAMP | Java | Só Conversa |

 


Acesso a AD - C#

  2008-03-06




Requesitos:
Importar biblioteca da framework relativa a DirectoryServices;
Usar credencias de um user com acesso à AD
(pode ser um Dummy criado para o efeito);

Podemos por exemplo criar uma classe ADHelper com as funções de acesso num projecto exemplo ADConnector:

 
using System;
using System.Collections.Generic;
using System.Text;
using System.DirectoryServices;
 
namespace ADConnector
{
class ADHelper
{
#region constants
public static String LDAP_DC = “dominio”;
public static String LDAP_User = “Dummy”;
public static String LDAP_Password = “password”;
#endregion
 
/// <summary>
/// Method to Connect to AD
/// </summary>
/// <returns></returns>
public static DirectoryEntry GetDirectoryEntry()
{
try
{
DirectoryEntry entry = new DirectoryEntry("LDAP://" + LDAP_DC,
LDAP_User, LDAP_Password);
return entry;
}
catch(Exception e)
{
Console.WriteLine(“Message: ” + e.Message + “Stack: ”+
e.StackTrace); return null;
}

}
 
/// <summary>
/// Secure Method to Connect to AD
/// </summary>
/// <returns></returns>
public static DirectoryEntry GetDirectoryEntryAuthenticationSecure()
{
try
{
DirectoryEntry entry = new DirectoryEntry("LDAP://" + LDAP_DC,
LDAP_User, LDAP_Password);
entry.AuthenticationType = AuthenticationTypes.Secure;
 
return entry;
}
catch(Exception e)
{
Console.WriteLine(“Message: ” + e.Message + “Stack: ”+
e.StackTrace); return null;
}
 

}
 
/// <summary>
/// Helper method that sets properties for AD users.
/// </summary>
/// <param name="de"></param>
/// <param name="PropertyName"></param>
/// <param name="PropertyValue"></param>
public static void SetProperty(DirectoryEntry de, String propertyName,
String propertyValue)
{
if (propertyValue != null)
{
if (de.Properties.Contains(propertyName))
{
de.Properties[propertyName][0] = propertyValue;
}
else
{
de.Properties[propertyName].Add(propertyValue);
}
}
}
 
/// <summary>
/// Method to validate if a user exists in the AD.
/// </summary>
/// <param name="UserName"></param>
/// <returns></returns>
public bool UserExists(string UserName)
{
DirectoryEntry de = GetDirectoryEntry();
DirectorySearcher deSearch = new DirectorySearcher();
deSearch.SearchRoot = de;
deSearch.Filter = "(&(objectClass=user) (cn=" + UserName + "))";
 
SearchResultCollection results = deSearch.FindAll();

if (results.Count == 0)
return false;
else
return true;

}

 
}
}
 
 



Podemos depois usar uma classe Managment que usa as ligações definidas para aceder à informação de todos os utilizadores na AD ou apenas de um utilizador em especifico, através de filtros, que no exemplo seguinte fazem-se nas funções por Login, Email e SamAccount (recomendo o último - sammaccount - pois funciona como o identifiador unico do utilizador)

 
using System;
using System.Collections.Generic;
using System.Text;
using System.DirectoryServices;
 
namespace ADConnector
{
public class ActiveDirectoryManagment
{
   //devolve informação de todos os users na AD
public static SearchResultCollection GetAllUserInfo()
{
DirectoryEntry entry = ADHelper.GetDirectoryEntry();

using (entry)
{
DirectorySearcher search = new DirectorySearcher();
search.SearchRoot = entry;
search.Filter =
"(&(objectCategory=Person)(objectClass=User))";
 
try
{
SearchResultCollection lista_resultados =
search.FindAll();
return lista_resultados;
}
catch (Exception e)
{
Console.WriteLine(“Message: ” + e.Message + “Stack: ”+
e.StackTrace); return null;
}
}

}
 
public static SearchResult GetUserInfoByLogin(String loginUser)
{
DirectoryEntry entry = ADHelper.GetDirectoryEntry();
 
if (entry != null)
{
DirectorySearcher deSearch = new DirectorySearcher();
deSearch.SearchRoot = entry;
deSearch.Filter = "(&(objectClass=user)(cn=" + loginUser +
"))";
deSearch.SearchScope = SearchScope.Subtree;
 
try
{
SearchResult sResultSet = deSearch.FindOne();
 
return sResultSet;
}
catch (Exception e)
{
Console.WriteLine(“Message: ” + e.Message + “Stack: ”+
e.StackTrace); return null;
}
}
else
{
return null;
}
}
 
public static SearchResult GetUserInfoByEmail(String email)
{
DirectoryEntry entry = ADHelper.GetDirectoryEntry();
 
if (entry != null)
{
DirectorySearcher deSearch = new DirectorySearcher();
deSearch.SearchRoot = entry;
deSearch.Filter =
"(&(objectCategory=Person)(objectClass=user)(mail=" + email + "))";
deSearch.SearchScope = SearchScope.Subtree;
 
try
{
SearchResult sResultSet = deSearch.FindOne();
 
return sResultSet;
}
catch (Exception e)
{
Console.WriteLine(“Message: ” + e.Message + “Stack: ”+ e.StackTrace); return
null;
}
}
else
{
return null;
}
 
}
 
public static SearchResult GetUserInfoBySamAcc(String samacc)
{
DirectoryEntry entry = ADHelper.GetDirectoryEntry();

if (entry != null)
{
DirectorySearcher deSearch = new DirectorySearcher();
deSearch.SearchRoot = entry;
deSearch.Filter =
"(&(objectCategory=Person)(objectClass=user)(sAMAccountName=" + samacc + "))";
deSearch.SearchScope = SearchScope.Subtree;
 
try
{
deSearch.FindAll();
SearchResult sResultSet = deSearch.FindOne();

return sResultSet;
}
catch (Exception e)
{
            Console.WriteLine(“Message: ” + e.Message + “Stack: ”+ e.StackTrace); return
null;
}
}
else
return null;
 
}
 
}
}
 

Depois de recolhidos os dados do SearchResult podemos então aceder a várias propriedades de cada user, no caso seguinte usamos uma função que preenche um objecto de utilizador com as propriedades que estão definidas na AD:

 
public void LoadUserBySamAcc(String samacc)
{
try
{
SearchResult sResultSet =
ActiveDirectoryManagment.GetUserInfoBySamAcc(samacc);
if (sResultSet.Properties.Contains("givenName") &&
sResultSet.Properties["givenName"][0] != null &&
sResultSet.Properties["givenName"][0].ToString().Length > 0)
this.UserName =
sResultSet.Properties["givenName"][0].ToString();
else
this.UserName = String.Empty;
 
if (sResultSet.Properties.Contains("mail") && sResultSet.Properties["mail"][0]
!= null && sResultSet.Properties["mail"][0].ToString().Length > 0)
this.UserEmail =
sResultSet.Properties["mail"][0].ToString();
else
this.UserEmail = String.Empty;
 
if (sResultSet.Properties.Contains("manager") &&
sResultSet.Properties["manager"][0] != null &&
sResultSet.Properties["manager"][0].ToString().Length > 0)
this.Manager =
sResultSet.Properties["manager"][0].ToString();
else
this.Manager= String.Empty;
 
 


Outras propriedade interessantes a que podemos aceder:
sAMAccountName
cn (Login Name)
sn (Last Name)
initials (Middle Initials)
title
co (Country)
company
department
homePostalAddress
st (state)
postalCode
telephoneNumber
whenCreated
whenChanged





Escrito por Tânia Penedo
Website do autor: http://www.taniapenedo.com
Dados do autor: Programação multi-plataforma; C#, PHP, Java, MySQL, SQL-Server.

Comentários

Faça um comentário

Comentário

Nome
E-mail

Este comentário só ficará válido depois de fazer clique no link que lhe será enviado já a seguir para o e-mail indicado. Como tal garanta que o seu e-mail está válido e operacional, se não receber o nosso e-mail verifique os seus filtros de SPAM, ou a caixa de Lixo/Trash do seu cliente de e-mail.

 

Avaliar artigo

Avalie este artigo

 



Nome
E-mail

Este voto só ficará contabilizado depois de fazer clique no link que lhe será enviado já a seguir para o e-mail indicado. Como tal garanta que o seu e-mail está válido e operacional, se não receber o nosso e-mail verifique os seus filtros de SPAM, ou a caixa de Lixo/Trash do seu cliente de e-mail.

 

 

 

 

Recomendar este artigo a alguém

Envie a alguém conhecido

De:  
Nome E-mail
 
Para:  
Nome E-mail
Será enviado um link da página deste artigo para o e-mail que indicar como destino.