2011-10-27 36 views
7

intentar acceder a un servidor ldap desde un servidor iis en dmz y obtener el mensaje de error: No se pudo recuperar la información (1355). Hay artículos sobre cómo agregar información de DNS o utilizar los objetos subyacentes, pero estas soluciones no me funcionan, así que por favor absténgase de buscar en Google y publicar los mismos malos consejos regurgitados.Acceso LDAP desde dmz falla:: no se pudo recuperar la información sobre el dominio (1355)

Reescribí toda la capa para usar objetos principales. Eso me dio un buen mensaje de error al menos.

using System; 
using System.Collections; 
using System.Collections.Generic; 
using System.DirectoryServices; 
using System.DirectoryServices.AccountManagement; 
using System.Linq; 
using System.Web; 
using TheDomain.Common.Extensions; 

namespace MobileApplications 
{ 
    public class Ldap35: IDisposable 
    { 
     private string _ldapserver; 
     private string _adminUser; 
     private string _adminPassword; 
     private PrincipalContext _connection; 
     private UserPrincipal _userData; 
     private IList<string> _groups; 

    public delegate void MessagingHandler(string message); 
    public event MessagingHandler Messaged; 

    public Ldap35(string server, string adminuser, string adminpassword) 
    { 
     _ldapserver = server; 
     _adminPassword = adminpassword; 
     _adminUser = adminuser; 
    } 
    /// <summary> 
    /// this will basically instantiate a UserPrincipal 
    /// </summary> 
    /// <param name="username">just the user</param> 
    /// <param name="pass">just the password</param> 
    /// <param name="domain">the correct domain, not sure if this is thedoamin.com or the_domain</param> 
    /// <returns></returns> 
    public bool Authenticate(string username, string pass, string domain) 
    { 
     if (_connection == null) 
      EstablishDirectoryConnection(); 

      ValidateConnection(); 
      if (!domain.IsEmpty() && !username.Contains("\\") && !username.Contains("/")) 
       username = domain + "\\" + username; 

      _userData = UserPrincipal.FindByIdentity(_connection, username); 

      if (_userData == null) 
       throw new ApplicationException("Unable to locate user."); 

      if (! _connection.ValidateCredentials(username, pass)) 
       throw new ApplicationException("Invalid credentials. Unable to log in."); 

      //_userData = new UserPrincipal(_connection, username, pass, true); 

      return true; 
    } 

    public bool Authenticate(string username, string pass) 
    { 
     return Authenticate(username, pass, ""); 
    } 

    public bool IsMemeberOfGroup(string group) 
    { 
     ValidateConnection(); ValidateUser(); 
     return _userData.IsMemberOf(new GroupPrincipal(_connection)); 
    } 

    public bool IsMemeberOfGroup(string group, bool caseSensitive) 
    { 
     if (caseSensitive) 
      return IsMemeberOfGroup(group); 

     GetGroups(); 

     return _groups.Any(g => g.ToLower().Trim() == group.ToLower().Trim()); 

    } 

//  public IList<string> GetGroups() 
//  { 
//   if (_groups == null) 
//    _groups = new List<string>(); 
// 
//   ValidateConnection(); ValidateUser(); 
//   
//    var results = _userData.GetGroups(); 
// 
//    foreach (var principal in results) 
//    { 
//     _groups.Add(principal.Name); 
//    } 
//   
//   return _groups; 
//  } 

    public IList<string> GetGroups() 
    { 
     if (_groups == null) 
      _groups = new List<string>(); 

     ValidateConnection(); ValidateUser(); 
     Print("Getting groups"); 
     DirectoryEntry de = (DirectoryEntry)_userData.GetUnderlyingObject(); 
     object obGroups = de.Invoke("Groups"); 
     foreach (object ob in (IEnumerable)obGroups) 
     { 
      // Create object for each group. 

      var obGpEntry = new DirectoryEntry(ob); 
      Print(obGpEntry.Name); 
      _groups.Add(obGpEntry.Name); 
     } 
     return _groups; 
    } 

    /// <summary> 
    /// PrincipalContext class to establish a connection to the target directory and specify credentials for performing operations against the directory. This approach is similar to how you would go about establishing context with the DirectoryContext class in the ActiveDirectory namespace. 
    /// </summary> 
    /// <param name="adminuser">a user with permissions on the domain controller</param> 
    /// <param name="adminpassword">the password to go with the above</param> 
    /// <returns></returns> 
    private void EstablishDirectoryConnection() 
    { 
     _connection = new PrincipalContext(ContextType.Domain, _ldapserver, "DC=thedomain,DC=com", ContextOptions.SimpleBind, _adminUser, _adminPassword); 
    } 

    private void Print(string message) 
    { 
     if (Messaged != null) 
      Messaged(message); 
    } 

    private void ValidateConnection() 
    { 
     if (_connection == null) 
      throw new ApplicationException("No connection to server, please check credentials and configuration."); 
    } 

    private void ValidateUser() 
    { 
     if (_userData == null) 
      throw new ApplicationException("User is not authenticated. Please verify username and password."); 
    } 

    public void Dispose() 
    { 
     _userData.Dispose(); 
     _connection.Dispose(); 
    } 
} 
} 
+0

por cierto, si alguien me puede decir cómo formatear correctamente mis fragmentos de código para que se muestren muy bien, eso sería una ventaja. No lo hago todo el tiempo por alguna razón –

+0

¿Puede el servidor incluso localizar y contactar a la fuente LDAP desde la DMZ? Normalmente, el acceso desde DMZ a la red interna está severamente restringido. Entonces la pregunta que puede necesitar para comenzar incluye: ¿Puede buscar el dominio en DNS? ¿Están abiertos los puertos 389 y/o 636? etc. – ewall

+0

puertos están abiertos y pueden telnet. restringirlo a la cuenta que está haciendo la búsqueda no puede ser la cuenta que estamos verificando –

Respuesta

7

Este artículo Active Directory - Adding a user to a group from a non domain-joined computer throws PrincipalException me señaló en la dirección correcta. Aunque realmente no tiene sentido. Me moví a un enfoque más moderno que he publicado anteriormente usando los PrincipalObjects tal como sigue:

var _connection = new PrincipalContext(ContextType.Domain, 
             _ldapserver, 
             "DC=domain,DC=com", 
             ContextOptions.SimpleBind, 
             _adminUser, 
             _adminPassword); 
var _userData = UserPrincipal.FindByIdentity(_connection, username); 

Esto me permitió pase en los permisos correctos para el controlador de dominio, pero a continuación, obtener método grupos en el objeto UserPrinicpal fue tirar el error 1155

Lo resolví utilizando el método anterior de la siguiente manera. Todo funciona bien ahora.

DirectoryEntry de = (DirectoryEntry)_userData.GetUnderlyingObject(); 
object obGroups = de.Invoke("Groups"); 
+3

Si usa ContextOptions.Simplebind, tenga en cuenta que la contraseña puede enviarse por Internet en texto sin cifrar. – ms007

Cuestiones relacionadas