2015-10-01 44 views
1

我在窗体中使用OpenLDAP实现登录用户。JavaEE 7 ldap登录方法

我想做一些简单的事情,不依赖于cointainer,所以我真的不想使用wildfly领域。

我能够制作一个表格和一个与OpenLDAP服务器正确连接的方法,但由于某种原因,它总是给我提供用户认证的错误。 (System.out.println(“用户正常,通过否”))

任何想法它可能是错的?

我的方法:

public static Boolean validateLogin(String userName, String userPassword) { 
    Hashtable<String, String> env = new Hashtable<String, String>(); 

    String LDAP_SERVER = "127.0.0.1"; 
    String LDAP_SERVER_PORT = "389"; 
    String LDAP_BASE_DN = "dc=domain,dc=moredata,dc=com"; 
    String LDAP_BIND_DN ="cn=user,dc=moredata,dc=com"; 
    String LDAP_BIND_PASSWORD ="mypassword"; 

    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); 
    env.put(Context.PROVIDER_URL, "ldap://" + LDAP_SERVER + ":" + LDAP_SERVER_PORT + "/" + LDAP_BASE_DN); 

    // To get rid of the PartialResultException when using Active Directory 
    env.put(Context.REFERRAL, "follow"); 

    // Needed for the Bind (User Authorized to Query the LDAP server) 
    env.put(Context.SECURITY_AUTHENTICATION, "simple"); 
    env.put(Context.SECURITY_PRINCIPAL, LDAP_BIND_DN); 
    env.put(Context.SECURITY_CREDENTIALS, LDAP_BIND_PASSWORD); 

    DirContext ctx; 
    try { 
     ctx = new InitialDirContext(env); 
    } catch (NamingException e) { 
     throw new RuntimeException(e); 
    } 

    NamingEnumeration<SearchResult> results = null; 

    try { 
     SearchControls controls = new SearchControls(); 
     controls.setSearchScope(SearchControls.SUBTREE_SCOPE); // Search Entire Subtree 
     controls.setCountLimit(1); //Sets the maximum number of entries to be returned as a result of the search 
     controls.setTimeLimit(5000); // Sets the time limit of these SearchControls in milliseconds 

     String searchString = "(&(objectCategory=users)(sAMAccountName=" + userName + "))"; 

     results = ctx.search("", searchString, controls); 

     if (results.hasMore()) { 

      SearchResult result = (SearchResult) results.next(); 
      Attributes attrs = result.getAttributes(); 
      Attribute dnAttr = attrs.get("distinguishedName"); 
      String dn = (String) dnAttr.get(); 

      // User Exists, Validate the Password 

      env.put(Context.SECURITY_PRINCIPAL, dn); 
      env.put(Context.SECURITY_CREDENTIALS, userPassword); 

      new InitialDirContext(env); // Exception will be thrown on Invalid case 
      //show validation suceed 
      System.out.println("Validation suceed"); 
      return true; 
     } 
     else 
      //User exist but password is wrong 
      System.out.println("User OK, pass no"); 
      return false; 

    } catch (AuthenticationException e) { // Invalid Login 

     //Tiro en consola el error 
     System.out.println("autentication error"); 
     return false; 
    } catch (NameNotFoundException e) { // The base context was not found. 

     return false; 
    } catch (SizeLimitExceededException e) { 
     throw new RuntimeException("LDAP Query Limit Exceeded, adjust the query to bring back less records", e); 
    } catch (NamingException e) { 
     throw new RuntimeException(e); 
    } finally { 

     if (results != null) { 
      try { results.close(); } catch (Exception e) { /* Do Nothing */ } 
     } 

     if (ctx != null) { 
      try { ctx.close(); } catch (Exception e) { /* Do Nothing */ } 
     } 
    } 
} 

我的形式是这样的:

<?xml version='1.0' encoding='UTF-8' ?> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" 
     xmlns:h="http://xmlns.jcp.org/jsf/html" 
     xmlns:f="http://xmlns.jcp.org/jsf/core" 
     xmlns:p="http://primefaces.org/ui" 
     xmlns:ui="http://xmlns.jcp.org/jsf/facelets"> 
    <h:head> 


     <title>Login LDAP</title> 
    </h:head> 
    <h:body> 

     <center> 
      <h2>Login</h2> 

<h:form id="Login" style="max-width: 50%; border: solid 1px; margin-bottom: 15px"> 
      <p:growl /> 
       <p:panelGrid columns="2" style="margin-top: 15px"> 

        <h:outputText value="Nombre" /> 
        <h:inputText id="nombre" value="#{authBean.userName}" required="true"/> 
        <h:outputText value="Password" /> 
        <h:inputSecret id="password" value="#{authBean.userPassword}" required="true"/> 
       </p:panelGrid> 



      <p:commandButton ajax="false" process="@all" update="@all" action="#{authBean.validateLogin(authBean.userName, authBean.userPassword)}" value="Login" /> 
      <br></br> 

       <br></br><br></br> 
       <hr></hr> 
       <small>Todos los campos son obligatorios</small> 
      </h:form> 
     </center> 


    </h:body> 
</html> 
+0

只是一个评论; void元素应该写为自闭标签。所以'
'而不是'

'; '


''而不是'
'等。某些浏览器中的错误处理将导致其中一些元素被复制。 –

+0

我知道,但由于某些原因,如果我没有两个标记(misterys),Netbeans有时无法部署应用程序 – Alexev

+0

如果可用,应该使用Container Manager身份验证。使一切变得更容易,并且它已经工作。 – EJP

回答

2

的方法工作

private String userName; 

    private String userPassword; 

    private String mensaje =""; 

public void validar(String usuario, String password) { 

     try { 
//Este metodo funciona para validar el usuario, 
//si el usuario tiene nombre y pass correcto devuelve un OK 
//Si el usuario da error entonces cierra la conexion 


//Generamos el DN   
final String dn = "uid=" + usuario +",ou=users,cn=admin,dc=organizacion,dc=com,dc=uy"; 

//Solicitamos el bindRequest creando una nueva instancia y de parametros el dn y pass 
     final BindRequest bindRequest = new SimpleBindRequest(dn, password); 
//Nos conectamos al server 
     final LDAPConnection ldapConnection = new LDAPConnection("192.168.1.1", 389); 
//Intentamos hacer el bind 
     final BindResult bindResult = ldapConnection.bind(bindRequest); 
//Obtenemos el resultcode de la funcion anterior (SUCCESS o FAIL) 
     final ResultCode resultCode = bindResult.getResultCode(); 



//Si el resultado es SUCESS entonces metemos el codigo aca 
// podemos iniciar una sesion, pasar valores a un session bean, etc 
     if (resultCode.equals(ResultCode.SUCCESS)) { 

      this.mensaje = "Validacion correcta"; 
     } else { 

      //Damos un error y cerramos la conexion 
      this.mensaje = "Validacion incorrecta"; 

      ldapConnection.close(); 

     } 
     } catch (Exception e) { 
      this.mensaje = "Mensaje de error"; 

     } 

来源: http://urupro.com/wp/2015/11/24/validando-usuarios-con-openldap-en-javaee/