public LdapContext createLdapContext ( final String userDn , final String password ) throws NamingException { LOGGER . debug ( "Creating LDAP context for: " + userDn ) ; if ( StringUtils . isEmpty ( userDn ) || StringUtils . isEmpty ( password ) ) { throw new NamingException ( "Username or password cannot be empty or null" ) ; } final Hashtable < String , String > env = new Hashtable <> ( ) ; if ( StringUtils . isNotBlank ( LDAP_SECURITY_AUTH ) ) { env . put ( Context . SECURITY_AUTHENTICATION , LDAP_SECURITY_AUTH ) ; } env . put ( Context . SECURITY_PRINCIPAL , userDn ) ; env . put ( Context . SECURITY_CREDENTIALS , password ) ; env . put ( Context . INITIAL_CONTEXT_FACTORY , "com.sun.jndi.ldap.LdapCtxFactory" ) ; env . put ( Context . PROVIDER_URL , LDAP_URL ) ; if ( IS_LDAP_SSLTLS ) { env . put ( "java.naming.ldap.factory.socket" , "alpine.crypto.RelaxedSSLSocketFactory" ) ; } try { return new InitialLdapContext ( env , null ) ; } catch ( CommunicationException e ) { LOGGER . error ( "Failed to connect to directory server" , e ) ; throw ( e ) ; } catch ( NamingException e ) { throw new NamingException ( "Failed to authenticate user" ) ; } }
Asserts a users credentials . Returns an LdapContext if assertion is successful or an exception for any other reason .