/** {@inheritDoc} */ public LDAPConnection getConnection() throws LDAPException { if (M_log.isDebugEnabled()) { M_log.debug("getConnection()"); } LDAPConnection conn = newConnection(); if (config.isAutoBind()) { if (M_log.isDebugEnabled()) { M_log.debug("getConnection(): auto-binding"); } try { bind(conn, config.getLdapUser(), config.getLdapPassword()); } catch (LDAPException ldape) { if (ldape.getResultCode() == LDAPException.INVALID_CREDENTIALS) { M_log.warn( "Failed to bind against: " + conn.getHost() + " with user: "******" password: "******".", "*")); } throw ldape; } } return conn; }
public boolean checkLdapLoginCredential(String userName, String userPassword) throws Exception { LDAPConnection lc = new LDAPConnection(); int ldapVersion = LDAPConnection.LDAP_V3; boolean ritorno = false; try { // check for required data if (isNullValue(ApplicationConfigurator.HOST) || (isNullValue(ApplicationConfigurator.PORT) && isNullValue(ApplicationConfigurator.PORT_SSL)) /* || isNullValue(ApplicationConfigurator.SEARCH_PATH) || isNullValue(ApplicationConfigurator.USER_DN_ATTRIBUTE_NAME) */ ) { throw new Exception("Dati obbligatori per la connessione ad LDAP non presenti."); } // Connect to the server try { lc.connect(ApplicationConfigurator.HOST, Integer.parseInt(ApplicationConfigurator.PORT)); } catch (Exception e) { e.printStackTrace(); throw e; } // Try login with user credential try { if (isNullValue(userName) || isNullValue(userPassword)) return false; userName = isNullValue(ApplicationConfigurator.USER_DN_ATTRIBUTE_NAME) ? userName : ApplicationConfigurator.USER_DN_ATTRIBUTE_NAME + "=" + userName; userName += isNullValue(ApplicationConfigurator.SEARCH_PATH) ? "" : "," + ApplicationConfigurator.SEARCH_PATH; lc.bind(ldapVersion, userName, userPassword); } catch (Exception e) { // Se si verifica un eccezione in questo punto significa che l'utente non è stato // trovato, per questo motivo risollevo l'eccezione con il messaggio standard di // utente e/o password errati. e.printStackTrace(); throw new Exception(ApplicationConfigurator.LanguageManager.getString("LDAP.Msg4")); } ritorno = true; } finally { // disconnect with the server lc.disconnect(); return ritorno; } }
public void disconnect() { try { connection.disconnect(); } catch (LDAPException e) { e.printStackTrace(); } }
private Vector getAttribute(String entryDN, String attr) { Vector v = new Vector(); LDAPSearchResults searchResults; LDAPEntry entry = null; try { searchResults = connection.search(entryDN, LDAPConnection.SCOPE_BASE, "", null, false); entry = searchResults.next(); } catch (LDAPException e) { // e.printStackTrace(); return v; } // System.out.println(entry); LDAPAttributeSet attributeSet = entry.getAttributeSet(); // System.out.println(attributeSet); Iterator allAttributes = attributeSet.iterator(); while (allAttributes.hasNext()) { LDAPAttribute attribute = (LDAPAttribute) allAttributes.next(); String attributeName = attribute.getName(); if (attributeName.equalsIgnoreCase(attr)) { Enumeration en = attribute.getStringValues(); for (; en.hasMoreElements(); ) { v.add(en.nextElement()); } } } return v; }
/** {@inheritDoc} */ public void returnConnection(LDAPConnection conn) { try { if (conn != null) conn.disconnect(); } catch (LDAPException e) { M_log.error("returnConnection(): failed on disconnect: ", e); } }
/** * Connects the specified <code>LDAPConnection</code> to the currently configured host and port. * * @param conn an <code>LDAPConnection</code> * @throws LDAPConnection if the connect attempt fails */ protected void connect(LDAPConnection conn) throws LDAPException { if (M_log.isDebugEnabled()) { M_log.debug("connect()"); } conn.connect(config.getLdapHost(), config.getLdapPort()); try { postConnect(conn); } catch (LDAPException e) { M_log.error( "Failed to completely initialize a connection [host = " + config.getLdapHost() + "][port = " + config.getLdapPort() + "]", e); try { conn.disconnect(); } catch (LDAPException ee) { } throw e; } catch (Throwable e) { M_log.error( "Failed to completely initialize a connection [host = " + config.getLdapHost() + "][port = " + config.getLdapPort() + "]", e); try { conn.disconnect(); } catch (LDAPException ee) { } if (e instanceof Error) { throw (Error) e; } if (e instanceof RuntimeException) { throw (RuntimeException) e; } throw new RuntimeException("LDAPConnection allocation failure", e); } }
/** {@inheritDoc} */ @Override public void abandon(final int messageId, final RequestControl[] controls) throws LdapException { try { connection.abandon(messageId, getLDAPConstraints(controls)); } catch (LDAPException e) { processLDAPException(e); } }
/** * Returns an ldap constraints object configured with the supplied controls. * * @param controls to sets in the constraints * @return ldap constraints */ protected LDAPConstraints getLDAPConstraints(final RequestControl[] controls) { LDAPConstraints constraints = connection.getConstraints(); if (constraints == null) { constraints = new LDAPConstraints(); } if (controls != null) { constraints.setControls(config.getControlProcessor().processRequestControls(controls)); } return constraints; }
private void bind(LDAPConnection conn, String dn, String pw) throws LDAPException { if (M_log.isDebugEnabled()) { M_log.debug("bind(): binding [dn = " + dn + "]"); } try { conn.bind(LDAPConnection.LDAP_V3, dn, pw.getBytes("UTF8")); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Failed to encode user password", e); } }
/** * Returns an ldap constraints object configured with the supplied request. * * @param request request containing configuration to create constraints * @return ldap constraints */ protected LDAPConstraints getLDAPConstraints(final Request request) { LDAPConstraints constraints = connection.getConstraints(); if (constraints == null) { constraints = new LDAPConstraints(); } if (request.getControls() != null) { constraints.setControls( config.getControlProcessor().processRequestControls(request.getControls())); } constraints.setReferralFollowing(request.getFollowReferrals()); return constraints; }
/** {@inheritDoc} */ @Override public void close(final RequestControl[] controls) throws LdapException { try { if (connection != null) { connection.disconnect(getLDAPConstraints(controls)); } } catch (LDAPException e) { throw new LdapException(e, ResultCode.valueOf(e.getResultCode())); } finally { connection = null; } }
/** {@inheritDoc} */ @Override public Response<Void> delete(final DeleteRequest request) throws LdapException { Response<Void> response = null; try { final LDAPResponseQueue queue = connection.delete(request.getDn(), (LDAPResponseQueue) null, getLDAPConstraints(request)); final LDAPResponse lr = (LDAPResponse) queue.getResponse(); response = createResponse(request, null, lr); } catch (LDAPException e) { processLDAPException(e); } return response; }
protected void postConnect(LDAPConnection conn) throws LDAPException { if (M_log.isDebugEnabled()) { M_log.debug("postConnect()"); } if (config.isSecureConnection() && isTlsSocketFactory()) { if (M_log.isDebugEnabled()) { M_log.debug("postConnect(): starting TLS"); } conn.startTLS(); } }
/** * Applies <code>LDAPConstraints</code> to the specified <code>LDAPConnection</code>. Implemented * to assign <code>timeLimit</code> and <code>referralFollowing</code> constraint values retrieved * from the currently assigned {@link LdapConnectionManagerConfig}. * * @param conn */ protected void applyConstraints(LDAPConnection conn) { int timeout = config.getOperationTimeout(); boolean followReferrals = config.isFollowReferrals(); if (M_log.isDebugEnabled()) { M_log.debug( "applyConstraints(): values [timeout = " + timeout + "][follow referrals = " + followReferrals + "]"); } LDAPConstraints constraints = new LDAPConstraints(); constraints.setTimeLimit(timeout); constraints.setReferralFollowing(followReferrals); conn.setConstraints(constraints); }
/** {@inheritDoc} */ @Override public Response<?> extendedOperation(final ExtendedRequest request) throws LdapException { Response<?> response = null; try { final LDAPExtendedResponse ldapExtRes = connection.extendedOperation( new LDAPExtendedOperation(request.getOID(), request.encode()), getLDAPConstraints(request)); final ExtendedResponse<?> extRes = ExtendedResponseFactory.createExtendedResponse( request.getOID(), ldapExtRes.getID(), ldapExtRes.getValue()); response = createResponse(request, extRes.getValue(), ldapExtRes); } catch (LDAPException e) { processLDAPException(e); } return response; }
/** {@inheritDoc} */ @Override public Response<Void> add(final AddRequest request) throws LdapException { Response<Void> response = null; try { final JLdapUtils bu = new JLdapUtils(); final LDAPResponseQueue queue = connection.add( new LDAPEntry(request.getDn(), bu.fromLdapAttributes(request.getLdapAttributes())), (LDAPResponseQueue) null, getLDAPConstraints(request)); final LDAPResponse lr = (LDAPResponse) queue.getResponse(); response = createResponse(request, null, lr); } catch (LDAPException e) { processLDAPException(e); } return response; }
/** * Executes an ldap search. * * @param conn to search with * @param sr to read properties from * @return ldap search queue * @throws LDAPException if an error occurs */ protected LDAPSearchQueue search(final LDAPConnection conn, final SearchRequest sr) throws LDAPException { final LDAPSearchConstraints constraints = getLDAPSearchConstraints(sr); final LDAPControl[] lc = config.getControlProcessor().processRequestControls(sr.getControls()); if (lc != null) { constraints.setControls(lc); } return conn.search( sr.getBaseDn(), getSearchScope(sr.getSearchScope()), sr.getSearchFilter() != null ? sr.getSearchFilter().format() : null, getReturnAttributes(sr), sr.getTypesOnly(), (LDAPSearchQueue) null, constraints); }
/** * Performs a simple bind. * * @param request to bind with * @return bind response * @throws LdapException if an error occurs */ protected Response<Void> simpleBind(final BindRequest request) throws LdapException { Response<Void> response = null; try { final LDAPResponseQueue queue = connection.bind( LDAPConnection.LDAP_V3, request.getDn(), request.getCredential().getBytes(), (LDAPResponseQueue) null, getLDAPConstraints(request)); final LDAPResponse lr = (LDAPResponse) queue.getResponse(); response = createResponse(request, null, lr); } catch (LDAPException e) { processLDAPException(e); } return response; }
/** * Performs an anonymous bind. * * @param request to bind with * @return bind response * @throws LdapException if an error occurs */ protected Response<Void> anonymousBind(final BindRequest request) throws LdapException { Response<Void> response = null; try { final LDAPResponseQueue queue = connection.bind( LDAPConnection.LDAP_V3, (String) null, (byte[]) null, (LDAPResponseQueue) null, getLDAPConstraints(request)); final LDAPResponse lr = (LDAPResponse) queue.getResponse(); response = createResponse(request, null, lr); } catch (LDAPException e) { processLDAPException(e); } return response; }
/** {@inheritDoc} */ @Override public Response<Boolean> compare(final CompareRequest request) throws LdapException { Response<Boolean> response = null; try { final JLdapUtils bu = new JLdapUtils(); final LDAPResponseQueue queue = connection.compare( request.getDn(), bu.fromLdapAttribute(request.getAttribute()), (LDAPResponseQueue) null, getLDAPConstraints(request)); final LDAPResponse lr = (LDAPResponse) queue.getResponse(); response = createResponse(request, lr.getResultCode() == ResultCode.COMPARE_TRUE.value(), lr); } catch (LDAPException e) { processLDAPException(e); } return response; }
/** * Performs a sasl bind. * * @param request to bind with * @return bind response * @throws LdapException if an error occurs */ protected Response<Void> saslBind(final BindRequest request) throws LdapException { try { final SaslConfig sc = request.getSaslConfig(); switch (sc.getMechanism()) { case EXTERNAL: throw new UnsupportedOperationException("SASL External not supported"); /* current implementation appears to be broken * see http://tinyurl.com/7ojdzlz * connection.bind( * (String) null, * sc.getAuthorizationId(), * new String[] {"EXTERNAL"}, * null, * (Object) null); * break; */ case DIGEST_MD5: connection.bind( (String) null, request.getDn(), new String[] {"DIGEST-MD5"}, null, new SaslCallbackHandler( null, request.getCredential() != null ? request.getCredential().getString() : null)); break; case CRAM_MD5: throw new UnsupportedOperationException("CRAM-MD5 not supported"); case GSSAPI: throw new UnsupportedOperationException("GSSAPI not supported"); default: throw new IllegalArgumentException( "Unknown SASL authentication mechanism: " + sc.getMechanism()); } } catch (LDAPException e) { processLDAPException(e); } return new Response<Void>(null, ResultCode.SUCCESS); }
/** * Sends the LDAPExtendedRequest to the ldap server using the specified, connection and registers * the listener with the parent polling thread. * * @param conn LDAPConnection for sending LDAPOperation. * @param requestoperation LDAPExtendedOperation to be send as LDAPExtendedRequest. * @param alistener The LDAPListener to be registered. * @throws LDAPException When the underlying operations on connection fails. */ private void sendExtendedRequest( final LDAPConnection conn, final LDAPExtendedOperation requestoperation, final LDAPEventListener alistener) throws LDAPException { LDAPResponseQueue queue = conn.extendedOperation(requestoperation, null, null); EdirEventsGenerator eventgenerator = null; int[] ids = queue.getMessageIDs(); if (ids.length == 1) { eventgenerator = new EdirEventsGenerator(alistener); super.pollforevents(queue, conn, eventgenerator, ids[0], this); } else { /// CLOVER:OFF throw new LDAPException(null, LDAPException.LOCAL_ERROR, "Unable to Obtain Message Id"); /// CLOVER:ON } }
/** {@inheritDoc} */ @Override public Response<Void> modifyDn(final ModifyDnRequest request) throws LdapException { Response<Void> response = null; try { final String[] dn = request.getNewDn().split(",", 2); final LDAPResponseQueue queue = connection.rename( request.getDn(), dn[0], dn[1], request.getDeleteOldRDn(), (LDAPResponseQueue) null, getLDAPConstraints(request)); final LDAPResponse lr = (LDAPResponse) queue.getResponse(); response = createResponse(request, null, lr); } catch (LDAPException e) { processLDAPException(e); } return response; }
public static void main(String[] args) { String ldapHost = "192.168.121.130"; String loginDN = "cn=admin,dc=ucweb,dc=com"; String password = "******"; String containerName = "dc=ucweb,dc=com"; int ldapPort = LDAPConnection.DEFAULT_SSL_PORT; int ldapVersion = LDAPConnection.LDAP_V3; LDAPJSSESecureSocketFactory ssf = new LDAPJSSESecureSocketFactory(TrustManager.createSSLSocketFactory()); LDAPConnection lc = new LDAPConnection(ssf); LDAPAttributeSet attributeSet = new LDAPAttributeSet(); attributeSet.add( new LDAPAttribute("objectclass", new String[] {new String("top"), new String("person")})); attributeSet.add(new LDAPAttribute("cn", "17")); attributeSet.add(new LDAPAttribute("sn", "17")); attributeSet.add(new LDAPAttribute("description", " ")); // attributeSet.add(new LDAPAttribute("userPassword", "111111")); String dn = "cn=17," + containerName; LDAPEntry newEntry = new LDAPEntry(dn, attributeSet); try { lc.connect(ldapHost, ldapPort); lc.bind(ldapVersion, loginDN, password.getBytes("UTF8")); System.out.println("login ldap server successfully."); lc.add(newEntry); System.out.println("Added object: " + dn + " successfully."); } catch (LDAPException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } finally { try { if (lc.isConnected()) { lc.disconnect(); } } catch (Exception e) { e.printStackTrace(); } } }
/** * Tests if the allowable lifetime of the given connection has already elapsed. Edge cases: * * <ol> * <li>Non-{@link PooledLDAPConnection} - returns <code>true</code> * <li><code>maxTtl</code> <= 0 - returns <code>true</code> * <li>Connection birthdate in the future - returns <code>true</code> * </ol> */ public boolean isConnectionAlive(LDAPConnection connectionToTest) { if (!(connectionToTest instanceof PooledLDAPConnection)) { if (log.isDebugEnabled()) { log.debug( "isConnectionAlive(): connection not of expected type [" + (connectionToTest == null ? "null" : connectionToTest.getClass().getName()) + "], returning true"); } return true; } if (maxTtl <= 0) { if (log.isDebugEnabled()) { log.debug("isConnectionAlive(): maxTtl set to infinite [" + maxTtl + "], returning true"); } return true; } long now = System.currentTimeMillis(); long then = ((PooledLDAPConnection) connectionToTest).getBirthdate(); long elapsed = now - then; boolean isAlive = elapsed <= maxTtl; if (log.isDebugEnabled()) { log.debug( "isConnectionAlive(): [now = " + now + "][then = " + then + "][elapsed = " + elapsed + "][max TTL = " + maxTtl + "][isAlive = " + isAlive + "]"); } return isAlive; }
public LDAPUser login(String aUserName, String aPassword) throws InvalidLoginException { LDAPUser onlineUser = null; try { connection.connect(ldapHost, ldapPort); System.out.println("Connect Successfull"); System.out.println(aUserName); LDAPSearchQueue searchResults = connection.search( "o=Aerothai", LDAPConnection.SCOPE_SUB, "cn=" + aUserName, new String[] {LDAPConnection.NO_ATTRS}, true, (LDAPSearchQueue) null); LDAPMessage message; message = searchResults.getResponse(); if (message instanceof LDAPSearchResult) { LDAPEntry entry = ((LDAPSearchResult) message).getEntry(); String dn = entry.getDN(); String[] userDn = dn.split(","); String fullDn = userDn[0] + "," + userDn[1] + "," + userDn[2] + ",o=Aerothai"; connection.bind(ldapVersion, fullDn, aPassword.getBytes("UTF8")); System.out.println("Bind Successfull"); onlineUser = new LDAPUser(); try { onlineUser.setFirstName((String) getAttribute(fullDn, "givenName").elementAt(0)); onlineUser.setLastName((String) getAttribute(fullDn, "sn").elementAt(0)); try { Integer.parseInt((String) getAttribute(fullDn, "cn").elementAt(1)); onlineUser.setEmployeeCode((String) getAttribute(fullDn, "cn").elementAt(1)); } catch (NumberFormatException e) { onlineUser.setEmployeeCode((String) getAttribute(fullDn, "cn").elementAt(0)); } onlineUser.setDepartment((String) getAttribute(fullDn, "ou").elementAt(0)); onlineUser.setLocation((userDn[2].split("="))[1]); } catch (ArrayIndexOutOfBoundsException e1) { e1.printStackTrace(); onlineUser = null; throw new InvalidLoginException( "à¡Ô´¤ÇÒÁ¼Ô´¾ÅÒ´ÃÐËÇèÒ§¡Òô֧¢éÍÁÙÅ ¡ÃØ³Ò Login ãËÁèÍÕ¡¤ÃÑé§"); } } else { disconnect(); throw new InvalidLoginException( "äÁ辺¼Ùéãªé§Ò¹ª×èÍ " + aUserName + " ¡ÃسÒÅͧÍÕ¡¤ÃÑé§ ËÃ×Í µÔ´µèÍà¨éÒ˹éÒ·Õè¡Í§Ç¤.¾Ç. à¾×è͵ÃǨÊͺ¢éÍÁÙŢͧ·èÒ¹"); } disconnect(); } catch (LDAPException e) { e.printStackTrace(); throw new InvalidLoginException( "ÃËÑʼèÒ¹äÁè¶Ù¡µéͧ ¡ÃسÒÅͧÍÕ¡¤ÃÑé§ ËÃ×Í µÔ´µèÍà¨éÒ˹éÒ·Õè¡Í§Ç¤.¾Ç. à¾×è͵ÃǨÊͺ¢éÍÁÙŢͧ·èÒ¹"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); throw new InvalidLoginException(e); } finally { disconnect(); } return onlineUser; }
/** * Creates a new jldap connection. * * @param conn ldap connection * @param pc provider configuration */ public JLdapConnection(final LDAPConnection conn, final JLdapProviderConfig pc) { connection = conn; config = pc; connection.addUnsolicitedNotificationListener(notificationListener); }