Foros del Web » Programación para mayores de 30 ;) » Java »

Metodo para valor usuario en OpenLDAP

Estas en el tema de Metodo para valor usuario en OpenLDAP en el foro de Java en Foros del Web. EDIT: El titulo debería ser "Metodo para validar usuario en OpenLDAP" , no puedo modificar el titulo, si un MOD lo puede hacer se lo ...
  #1 (permalink)  
Antiguo 05/10/2015, 08:17
Avatar de Hyemin  
Fecha de Ingreso: agosto-2014
Mensajes: 147
Antigüedad: 9 años, 8 meses
Puntos: 0
Metodo para valor usuario en OpenLDAP

EDIT: El titulo debería ser "Metodo para validar usuario en OpenLDAP", no puedo modificar el titulo, si un MOD lo puede hacer se lo agradezco

Estoy trabajando en un metodo para validar usuarios contra un OpenLDAP, se que se puede hacer por medio de "container validation2 pero realmente no quiero depender del contenedor, quiero hacer algo que funcione para Tomcat, Wildfly e incluso Glassfish.

Por ahora logre hacer un metodo y el logeo me da que se conecta bien al OpenLDAP, le puse 3 salidas a terminal solo para ver si lo hace bien, una para cuando el user esta bien pero el password no, otra cuando el user esta mal y otra cuando ambos estan bien.

Siempre me sale el mismo error (el de user OK y pass mal).

Estuve haciendo debugging y al parecer el error esta en el string que hace de la consulta, pero no estoy pudiendo dar con el clavo para corregirlo

El metodo

Código Java:
Ver original
  1. public static Boolean validateLogin(String userName, String userPassword) {
  2.     Hashtable<String, String> env = new Hashtable<String, String>();
  3.  
  4.     String LDAP_SERVER = "127.0.0.1";
  5.     String LDAP_SERVER_PORT = "389";
  6.     String LDAP_BASE_DN = "dc=domain,dc=moredata,dc=com";
  7.     String LDAP_BIND_DN ="cn=user,dc=moredata,dc=com";
  8.     String LDAP_BIND_PASSWORD ="mypassword";
  9.  
  10.     env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
  11.     env.put(Context.PROVIDER_URL, "ldap://" + LDAP_SERVER + ":" + LDAP_SERVER_PORT + "/" + LDAP_BASE_DN);
  12.  
  13.     // To get rid of the PartialResultException when using Active Directory
  14.     env.put(Context.REFERRAL, "follow");
  15.  
  16.     // Needed for the Bind (User Authorized to Query the LDAP server)
  17.     env.put(Context.SECURITY_AUTHENTICATION, "simple");
  18.     env.put(Context.SECURITY_PRINCIPAL, LDAP_BIND_DN);
  19.     env.put(Context.SECURITY_CREDENTIALS, LDAP_BIND_PASSWORD);
  20.  
  21.     DirContext ctx;
  22.     try {
  23.        ctx = new InitialDirContext(env);
  24.     } catch (NamingException e) {
  25.        throw new RuntimeException(e);
  26.     }
  27.  
  28.     NamingEnumeration<SearchResult> results = null;
  29.  
  30.     try {
  31.        SearchControls controls = new SearchControls();
  32.        controls.setSearchScope(SearchControls.SUBTREE_SCOPE); // Search Entire Subtree
  33.        controls.setCountLimit(1);   //Sets the maximum number of entries to be returned as a result of the search
  34.        controls.setTimeLimit(5000); // Sets the time limit of these SearchControls in milliseconds
  35.  
  36.        String searchString = "(&(objectCategory=users)(sAMAccountName=" + userName + "))";
  37.  
  38.        results = ctx.search("", searchString, controls);
  39.  
  40.        if (results.hasMore()) {
  41.  
  42.            SearchResult result = (SearchResult) results.next();
  43.            Attributes attrs = result.getAttributes();
  44.            Attribute dnAttr = attrs.get("distinguishedName");
  45.            String dn = (String) dnAttr.get();
  46.  
  47.            // User Exists, Validate the Password
  48.  
  49.            env.put(Context.SECURITY_PRINCIPAL, dn);
  50.            env.put(Context.SECURITY_CREDENTIALS, userPassword);
  51.  
  52.            new InitialDirContext(env); // Exception will be thrown on Invalid case
  53.            //show validation suceed
  54.            System.out.println("Validation suceed");
  55.            return true;
  56.        }
  57.        else
  58.            //User exist but password is wrong
  59.            System.out.println("User OK, pass no");
  60.            return false;
  61.  
  62.     } catch (AuthenticationException e) { // Invalid Login
  63.  
  64.         //Tiro en consola el error
  65.         System.out.println("autentication error");
  66.         return false;
  67.     } catch (NameNotFoundException e) { // The base context was not found.
  68.  
  69.         return false;
  70.     } catch (SizeLimitExceededException e) {
  71.         throw new RuntimeException("LDAP Query Limit Exceeded, adjust the query to bring back less records", e);
  72.     } catch (NamingException e) {
  73.        throw new RuntimeException(e);
  74.     } finally {
  75.  
  76.        if (results != null) {
  77.           try { results.close(); } catch (Exception e) { /* Do Nothing */ }
  78.        }
  79.  
  80.        if (ctx != null) {
  81.           try { ctx.close(); } catch (Exception e) { /* Do Nothing */ }
  82.        }
  83.     }
  84. }

El formulario

Código HTML:
Ver original
  1. <?xml version='1.0' encoding='UTF-8' ?>
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  3. <html xmlns="http://www.w3.org/1999/xhtml"
  4.      xmlns:h="http://xmlns.jcp.org/jsf/html"
  5.      xmlns:f="http://xmlns.jcp.org/jsf/core"
  6.      xmlns:p="http://primefaces.org/ui"
  7.      xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
  8.     <h:head>
  9.  
  10.  
  11.         <title>Login LDAP</title>
  12.     </h:head>
  13.     <h:body>
  14.  
  15.         <center>
  16.             <h2>Login</h2>
  17.  
  18. <h:form  id="Login" style="max-width: 50%; border: solid 1px; margin-bottom: 15px">
  19.             <p:growl />
  20.                 <p:panelGrid columns="2" style="margin-top: 15px">
  21.  
  22.                     <h:outputText value="Nombre" />  
  23.                     <h:inputText id="nombre" value="#{authBean.userName}" required="true"/>
  24.                     <h:outputText value="Password" />  
  25.                     <h:inputSecret id="password" value="#{authBean.userPassword}" required="true"/>
  26.                 </p:panelGrid>
  27.  
  28.  
  29.  
  30.             <p:commandButton  ajax="false" process="@all" update="@all"  action="#{authBean.validateLogin(authBean.userName, authBean.userPassword)}" value="Login" />
  31.             <br></br>
  32.  
  33.                 <br></br><br></br>
  34.                 <hr></hr>
  35.                 <small>Todos los campos son obligatorios</small>
  36.             </h:form>
  37.         </center>
  38.  
  39.  
  40.     </h:body>
  41. </html>

Etiquetas: metodo, string, usuario, valor
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 19:10.