2008-11-27 21 views
11

¿Cómo se busca un usuario en Active Directory?.NET: ¿Cómo buscar un usuario en Active Directory?

Algunos nombres de usuario de ejemplo son:

Es importante tener en cuenta que no sé el nombre del dominio, and i shouldn't be hard-coding it.

Hay algunos sample code on stack-overflow que fallan.

using System.DirectoryServices; 

/// <summary> 
/// Gets the email address, if defined, of a user from Active Directory. 
/// </summary> 
/// <param name="userid">The userid of the user in question. Make 
/// sure the domain has been stripped first!</param> 
/// <returns>A string containing the user's email address, or null 
/// if one was not defined or found.</returns> 
public static string GetEmail(string userid) 
{ 
    DirectorySearcher searcher; 
    SearchResult result; 
    string email; 

    // Check first if there is a slash in the userid 
    // If there is, domain has not been stripped 
    if (!userid.Contains("\\")) 
    { 
     searcher = new DirectorySearcher(); 
     searcher.Filter = String.Format("(SAMAccountName={0})", userid); 
     searcher.PropertiesToLoad.Add("mail"); 
     result = searcher.FindOne(); 
     if (result != null) 
     { 
      email = result.Properties["mail"][0].ToString(); 
     } 
    } 

    return email; 
} 

Asegura específicamente que no haya pasado un nombre de usuario completo. p.ej.

Bad: avatopia\ian 
Bad: avatar\ian 
Good: ian 
Good: ian 

Debido a que no se le permite pasar del dominio, no puede diferenciar entre los dos usuarios

ian 
ian 

Otro tipo tiene the same question en sackoverflow, pero la respuesta aceptada dice que usted debe

primero localice el contexto de nomenclatura para el dominio requerido

i don't know qué es un "contexto de denominación", y no sé qué es el "dominio requerido". Realmente preferiría no escribir una expresión regular para tratar de analizar los nombres de usuario en nombres de dominio y cuentas, por ej.

domain.something\user-name 

en

domain.something 
user-name 

porque sé que habrá algún caso extremo de que voy a conseguir equivocado. Quiero el método adecuado y pretendido para buscar a un usuario en el directorio activo.

Hay una buena página en CodeProject How to do almost everything in Active Directory, pero no se puede buscar información de un usuario por nombre de usuario

espero que yo pueda dar mi controlador de dominio (whoever it is, where ever it is, whatever it's called) un nombre de usuario, y se darán cuenta de qué dominio ese usuario pertenece, hable con ese controlador de dominio y realice el trabajo.

Respuesta

5

Esto funciona para mí.

Debería poder diferenciar entre diferentes usuarios en diferentes controladores de dominio (es decir, dominio/nombre de usuario) porque los ldappaths serán diferentes. Y según usted no le importa porque es not specifying an ldappath.

Usted está haciendo una oferta sobre la eliminación del dominio/de User.Identity.Name. pero no estoy seguro de lo que te preocupa, solo tienes que cortar la cuerda en dos mitades la primera vez que te encuentres 'es hora de cortar.

y si no le gusta que se puede utilizar el "camino correcto": http://msdn.microsoft.com/en-us/library/ms973834.aspx

esto también es bueno http://geekswithblogs.net/mhamilton/archive/2005/09/30/55621.aspx

 /// This is some imaginary code to show you how to use it 

     Session["USER"] = User.Identity.Name.ToString(); 
     Session["LOGIN"] = RemoveDomainPrefix(User.Identity.Name.ToString()); // not a real function :D 
     string ldappath = "LDAP://your_ldap_path"; 
     // "LDAP://CN=<group name>, CN =<Users>, DC=<domain component>, DC=<domain component>,..." 


     Session["cn"] = GetAttribute(ldappath, (string)Session["LOGIN"], "cn"); 
     Session["displayName"] = GetAttribute(ldappath, (string)Session["LOGIN"], "displayName"); 
     Session["mail"] = GetAttribute(ldappath, (string)Session["LOGIN"], "mail"); 
     Session["givenName"] = GetAttribute(ldappath, (string)Session["LOGIN"], "givenName"); 
     Session["sn"] = GetAttribute(ldappath, (string)Session["LOGIN"], "sn"); 


/// working code 

public static string GetAttribute(string ldappath, string sAMAccountName, string attribute) 
    { 
     string OUT = string.Empty; 

     try 
     { 
      DirectoryEntry de = new DirectoryEntry(ldappath); 
      DirectorySearcher ds = new DirectorySearcher(de); 
      ds.Filter = "(&(objectClass=user)(objectCategory=person)(sAMAccountName=" + sAMAccountName + "))"; 

      SearchResultCollection results = ds.FindAll(); 

      foreach (SearchResult result in ds.FindAll()) 
      { 
       OUT = GetProperty(result, attribute); 
      } 
     } 
     catch (Exception t) 
     { 
      // System.Diagnostics.Debug.WriteLine(t.Message); 
     } 

     return (OUT != null) ? OUT : string.Empty; 
    } 

public static string GetProperty(SearchResult searchResult, string PropertyName) 
    { 
     if (searchResult.Properties.Contains(PropertyName)) 
     { 
      return searchResult.Properties[PropertyName][0].ToString(); 
     } 
     else 
     { 
      return string.Empty; 
     } 
    } 

Para dominio/nombre de usuario

public static string GetDomain(string s) 
    { 
     int stop = s.IndexOf("\\"); 
     return (stop > -1) ? s.Substring(0, stop + 1) : null; 
    } 

    public static string GetLogin(string s) 
    { 
     int stop = s.IndexOf("\\"); 
     return (stop > -1) ? s.Substring(stop + 1, s.Length - stop - 1) : null; 
    } 

Para el estilo de nombre de usuario @ dominio

public static string GetDomain(string s) //untested 
    { 
     int stop = s.IndexOf("@"); 
     return (stop > -1) ? s.Substring(stop + 1, s.Length - stop - 1) : null; 
    } 


    public static string GetLogin(string s) //untested 
    { 
     int stop = s.IndexOf("@"); 
     return (stop > -1) ? s.Substring(0, stop) : null; 
    } 
+0

Tiene un código que se divide 'ian @ avatopia.local' –

+0

quizás .. vea arriba – inspite

Cuestiones relacionadas