JavaEE 7 ldap登录方法

时间:2015-10-01 16:44:31

标签: java openldap

我正在使用表格来登录用户以反对OpenLDAP实施。

我想做一些简单的事情,不依赖于投币器,所以我真的不想使用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>

1 个答案:

答案 0 :(得分:2)