List of usage examples for javax.naming.directory DirContext close
public void close() throws NamingException;
From source file:org.picketlink.idm.performance.TestBase.java
public void cleanUpDN(String dn) throws Exception { DirContext ldapCtx = getLdapContext(); try {/*w ww. j ava2s . c o m*/ logger.fine("Removing: " + dn); removeContext(ldapCtx, dn); } catch (Exception e) { // } finally { ldapCtx.close(); } }
From source file:es.udl.asic.user.OpenLdapDirectoryProvider.java
public boolean authenticateUser(String userLogin, UserEdit edit, String password) { Hashtable env = new Hashtable(); InitialDirContext ctx;//ww w . j av a 2s. co m String INIT_CTX = "com.sun.jndi.ldap.LdapCtxFactory"; String MY_HOST = getLdapHost() + ":" + getLdapPort(); String cn; boolean returnVal = false; if (!password.equals("")) { env.put(Context.INITIAL_CONTEXT_FACTORY, INIT_CTX); env.put(Context.PROVIDER_URL, MY_HOST); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_CREDENTIALS, "secret"); String[] returnAttribute = { "ou" }; SearchControls srchControls = new SearchControls(); srchControls.setReturningAttributes(returnAttribute); srchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); String searchFilter = "(&(objectclass=person)(uid=" + escapeSearchFilterTerm(userLogin) + "))"; try { ctx = new InitialDirContext(env); NamingEnumeration answer = ctx.search(getBasePath(), searchFilter, srchControls); String trobat = "false"; while (answer.hasMore() && trobat.equals("false")) { SearchResult sr = (SearchResult) answer.next(); String dn = sr.getName().toString() + "," + getBasePath(); // Second binding Hashtable authEnv = new Hashtable(); try { authEnv.put(Context.INITIAL_CONTEXT_FACTORY, INIT_CTX); authEnv.put(Context.PROVIDER_URL, MY_HOST); authEnv.put(Context.SECURITY_AUTHENTICATION, "simple"); authEnv.put(Context.SECURITY_PRINCIPAL, sr.getName() + "," + getBasePath()); authEnv.put(Context.SECURITY_CREDENTIALS, password); try { DirContext authContext = new InitialDirContext(authEnv); returnVal = true; trobat = "true"; authContext.close(); } catch (AuthenticationException ae) { M_log.info("Access forbidden"); } } catch (NamingException namEx) { M_log.info("User doesn't exist"); returnVal = false; namEx.printStackTrace(); } } if (trobat.equals("false")) returnVal = false; } catch (NamingException namEx) { namEx.printStackTrace(); returnVal = false; } } return returnVal; }
From source file:org.malaguna.cmdit.service.ldap.LDAPBase.java
public Attributes loadUser(String uid, String[] attrs) { // Preparar las variables de entorno para la conexin JNDI Hashtable<String, String> entorno = new Hashtable<String, String>(); // Credenciales del usuario para realizar la bsqueda String cadena = "uid=" + user + "," + context; entorno.put(Context.PROVIDER_URL, server); entorno.put(Context.INITIAL_CONTEXT_FACTORY, initContext); if (password != null && user != null) { entorno.put(Context.SECURITY_PRINCIPAL, cadena); entorno.put(Context.SECURITY_CREDENTIALS, password); }//from w ww.j a v a 2 s . c o m Attributes atributos = null; try { // Crear contexto de directorio inicial DirContext ctx = new InitialDirContext(entorno); // Recuperar atributos del usuario que se est buscando if (attrs != null) atributos = ctx.getAttributes("uid=" + uid + "," + context, attrs); else atributos = ctx.getAttributes("uid=" + uid + "," + context); // Cerrar la conexion ctx.close(); } catch (NamingException e) { logger.error(messages.getMessage("err.ldap.attribute", new Object[] { e }, Locale.getDefault())); } return atributos; }
From source file:com.predic8.membrane.core.interceptor.authentication.session.LDAPUserDataProvider.java
/** * @throws NoSuchElementException if no user could be found with the given login * @throws AuthenticationException if the password does not match * @throws CommunicationException e.g. on server timeout * @throws NamingException on any other LDAP error *//*from ww w. j ava 2 s . c o m*/ private HashMap<String, String> auth(String login, String password) throws NamingException { Hashtable<String, String> env = new Hashtable<String, String>(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, url); env.put("com.sun.jndi.ldap.read.timeout", timeout); env.put("com.sun.jndi.ldap.connect.timeout", connectTimeout); if (binddn != null) { env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, binddn); env.put(Context.SECURITY_CREDENTIALS, bindpw); } HashMap<String, String> userAttrs = new HashMap<String, String>(); String uid; DirContext ctx = new InitialDirContext(env); try { uid = searchUser(login, userAttrs, ctx); } finally { ctx.close(); } if (passwordAttribute != null) { if (!userAttrs.containsKey("_pass")) throw new NoSuchElementException(); String pass = userAttrs.get("_pass"); if (pass == null || !pass.startsWith("{x-plain}")) throw new NoSuchElementException(); log.debug("found password"); pass = pass.substring(9); if (!pass.equals(password)) throw new NoSuchElementException(); userAttrs.remove("_pass"); } else { env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, uid + "," + base); env.put(Context.SECURITY_CREDENTIALS, password); DirContext ctx2 = new InitialDirContext(env); try { if (readAttributesAsSelf) searchUser(login, userAttrs, ctx2); } finally { ctx2.close(); } } return userAttrs; }
From source file:it.infn.ct.security.utilities.LDAPUtils.java
public static boolean isCNregistered(String cn) { boolean registered = false; NamingEnumeration results = null; DirContext ctx = null; try {//from w w w. j av a 2 s . c om ctx = getContext(); SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); ResourceBundle rb = ResourceBundle.getBundle("ldap"); results = ctx.search(rb.getString("peopleRoot"), "(cn=" + cn + ")", controls); if (results.hasMore()) { registered = true; } } catch (NameNotFoundException ex) { _log.error(ex); } catch (NamingException e) { registered = true; } finally { if (results != null) { try { results.close(); } catch (Exception e) { // Never mind this. } } if (ctx != null) { try { ctx.close(); } catch (Exception e) { // Never mind this. } } } return registered; }
From source file:it.infn.ct.security.utilities.LDAPUtils.java
public static boolean isMailUsed(String mail) { boolean registered = false; NamingEnumeration results = null; DirContext ctx = null; try {// w w w .ja v a 2s .c om ctx = getContext(); SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); ResourceBundle rb = ResourceBundle.getBundle("ldap"); results = ctx.search(rb.getString("peopleRoot"), "(mail=" + mail + ")", controls); if (results.hasMore()) { registered = true; } } catch (NameNotFoundException ex) { _log.error(ex); } catch (NamingException e) { registered = true; } finally { if (results != null) { try { results.close(); } catch (Exception e) { // Never mind this. } } if (ctx != null) { try { ctx.close(); } catch (Exception e) { // Never mind this. } } } return registered; }
From source file:de.sub.goobi.helper.ldap.Ldap.java
/** * create new user in LDAP-directory.//from ww w . j a v a2 s .co m * * @param inBenutzer * User object * @param inPasswort * String */ public void createNewUser(User inBenutzer, String inPasswort) throws NamingException, NoSuchAlgorithmException, IOException { if (!ConfigCore.getBooleanParameter("ldap_readonly", false)) { Hashtable<String, String> env = getLdapConnectionSettings(); env.put(Context.SECURITY_PRINCIPAL, ConfigCore.getParameter("ldap_adminLogin")); env.put(Context.SECURITY_CREDENTIALS, ConfigCore.getParameter("ldap_adminPassword")); LdapUser dr = new LdapUser(); dr.configure(inBenutzer, inPasswort, getNextUidNumber()); DirContext ctx = new InitialDirContext(env); ctx.bind(getUserDN(inBenutzer), dr); ctx.close(); setNextUidNumber(); Helper.setMeldung(null, Helper.getTranslation("ldapWritten") + " " + serviceManager.getUserService().getFullName(inBenutzer), ""); /* * check if HomeDir exists, else create it */ logger.debug("HomeVerzeichnis pruefen"); URI homePath = URI.create(getUserHomeDirectory(inBenutzer)); if (!new File(homePath).exists()) { logger.debug("HomeVerzeichnis existiert noch nicht"); serviceManager.getFileService().createDirectoryForUser(homePath, inBenutzer.getLogin()); logger.debug("HomeVerzeichnis angelegt"); } else { logger.debug("HomeVerzeichnis existiert schon"); } } else { Helper.setMeldung(Helper.getTranslation("ldapIsReadOnly")); } }
From source file:org.keycloak.testsuite.federation.kerberos.AbstractKerberosTest.java
protected String invokeLdap(GSSCredential gssCredential, String username) throws NamingException { Hashtable env = new Hashtable(11); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, "ldap://localhost:10389"); if (gssCredential != null) { env.put(Context.SECURITY_AUTHENTICATION, "GSSAPI"); env.put(Sasl.CREDENTIALS, gssCredential); }//w w w. ja va2 s . co m DirContext ctx = new InitialDirContext(env); try { Attributes attrs = ctx.getAttributes("uid=" + username + ",ou=People,dc=keycloak,dc=org"); String cn = (String) attrs.get("cn").get(); String sn = (String) attrs.get("sn").get(); return cn + " " + sn; } finally { ctx.close(); } }
From source file:com.googlecode.fascinator.authentication.custom.ldap.CustomLdapAuthenticationHandler.java
/** * Attempts to authenticate user credentials with the LDAP server * //from w ww.ja va 2s .c om * @param username * a username * @param password * a password * @param dn * if precise dn known, otherwise should be empty string * @return <code>true</code> if authentication was successful, * <code>false</code> otherwise */ private boolean bind(String username, String password) { try { String principal = String.format("%s=%s,%s", idAttr, username, baseDn); env.put(Context.SECURITY_PRINCIPAL, principal); env.put(Context.SECURITY_CREDENTIALS, password); DirContext ctx = new InitialDirContext(env); ctx.lookup(principal); ctx.close(); return true; } catch (NamingException ne) { log.warn("Failed LDAP lookup doAuthenticate", ne); } return false; }
From source file:com.photon.phresco.ldap.impl.LDAPManagerImpl.java
@Override public User authenticate(Credentials credentials) throws PhrescoException { if (isDebugEnabled) { S_LOGGER.debug("Entering Method LDAPManagerImpl.authenticate(Credentials credentials)"); }/* ww w . j a v a 2 s . c o m*/ String userName = credentials.getUsername(); String passwordEncoded = credentials.getPassword(); byte[] decodedBytes = Base64.decodeBase64(passwordEncoded); String password = new String(decodedBytes); Properties env = new Properties(); env.put(Context.INITIAL_CONTEXT_FACTORY, ldapConfig.getLdapContextFactory()); env.put(Context.PROVIDER_URL, ldapConfig.getLdapUrl()); env.put(Context.SECURITY_PRINCIPAL, getUserPrincipal(userName)); env.put(Context.SECURITY_CREDENTIALS, password); DirContext dc = null; try { dc = new InitialDirContext(env); if (isDebugEnabled) { S_LOGGER.debug("authenticate() Login Success for " + userName); } return getUser(credentials, dc); } catch (Exception e) { e.printStackTrace(); if (isDebugEnabled) { S_LOGGER.debug("authenticate() Login Failed for " + userName); } return new User(); } finally { try { if (dc != null) { dc.close(); } } catch (NamingException e) { throw new PhrescoException(e); } } }