List of usage examples for javax.naming.ldap LdapContext addToEnvironment
public Object addToEnvironment(String propName, Object propVal) throws NamingException;
From source file:info.jtrac.acegi.JtracLdapAuthenticationProvider.java
/** * displayName and mail are returned always, the map allows us to support * getting arbitrary properties in the future, hopefully *//*from w ww .j a v a2 s. c o m*/ public Map<String, String> bind(String loginName, String password) throws Exception { Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, ldapUrl); env.put(Context.SECURITY_AUTHENTICATION, "simple"); LdapContext ctx = null; if (activeDirectoryDomain != null) { // we are using Active Directory Control[] controls = new Control[] { control }; ctx = new InitialLdapContext(env, controls); logger.debug("Active Directory LDAP context initialized"); ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, activeDirectoryDomain + "\\" + loginName); ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password); // javax.naming.AuthenticationException ctx.reconnect(controls); logger.debug("Active Directory LDAP bind successful"); } else { // standard LDAP env.put(Context.SECURITY_PRINCIPAL, searchKey + "=" + loginName + "," + searchBase); env.put(Context.SECURITY_CREDENTIALS, password); ctx = new InitialLdapContext(env, null); logger.debug("Standard LDAP bind successful"); } SearchControls sc = new SearchControls(); sc.setSearchScope(SearchControls.SUBTREE_SCOPE); sc.setReturningAttributes(returningAttributes); NamingEnumeration results = ctx.search(searchBase, searchKey + "=" + loginName, sc); while (results.hasMoreElements()) { SearchResult sr = (SearchResult) results.next(); Attributes attrs = sr.getAttributes(); logger.debug("attributes: " + attrs); Map<String, String> map = new HashMap<String, String>(returningAttributes.length); for (String key : returningAttributes) { Attribute attr = attrs.get(key); if (attr != null) { map.put(key, (String) attr.get()); } } return map; // there should be only one anyway } // if we reached here, there was no search result throw new Exception("no results returned from ldap"); }
From source file:de.sub.goobi.helper.ldap.Ldap.java
/** * retrieve home directory of given user. * * @param inBenutzer// w w w . java 2 s.c om * User object * @return path as string */ public String getUserHomeDirectory(User inBenutzer) { if (ConfigCore.getBooleanParameter("useLocalDirectory", false)) { return ConfigCore.getParameter("dir_Users") + inBenutzer.getLogin(); } Hashtable<String, String> env = getLdapConnectionSettings(); if (ConfigCore.getBooleanParameter("ldap_useTLS", false)) { env = new Hashtable<>(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, ConfigCore.getParameter("ldap_url")); env.put("java.naming.ldap.version", "3"); LdapContext ctx = null; StartTlsResponse tls = null; try { ctx = new InitialLdapContext(env, null); // Authentication must be performed over a secure channel tls = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest()); tls.negotiate(); // Authenticate via SASL EXTERNAL mechanism using client X.509 // certificate contained in JVM keystore ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple"); ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, ConfigCore.getParameter("ldap_adminLogin")); ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, ConfigCore.getParameter("ldap_adminPassword")); ctx.reconnect(null); Attributes attrs = ctx.getAttributes(getUserDN(inBenutzer)); Attribute la = attrs.get("homeDirectory"); return (String) la.get(0); // Perform search for privileged attributes under authenticated // context } catch (IOException e) { logger.error("TLS negotiation error:", e); return ConfigCore.getParameter("dir_Users") + inBenutzer.getLogin(); } catch (NamingException e) { logger.error("JNDI error:", e); return ConfigCore.getParameter("dir_Users") + inBenutzer.getLogin(); } finally { if (tls != null) { try { // Tear down TLS connection tls.close(); } catch (IOException e) { logger.error(e); } } if (ctx != null) { try { // Close LDAP connection ctx.close(); } catch (NamingException e) { logger.error(e); } } } } else if (ConfigCore.getBooleanParameter("useSimpleAuthentification", false)) { env.put(Context.SECURITY_AUTHENTICATION, "none"); } else { env.put(Context.SECURITY_PRINCIPAL, ConfigCore.getParameter("ldap_adminLogin")); env.put(Context.SECURITY_CREDENTIALS, ConfigCore.getParameter("ldap_adminPassword")); } DirContext ctx; String rueckgabe = ""; try { ctx = new InitialDirContext(env); Attributes attrs = ctx.getAttributes(getUserDN(inBenutzer)); Attribute la = attrs.get("homeDirectory"); rueckgabe = (String) la.get(0); ctx.close(); } catch (NamingException e) { logger.error(e); } return rueckgabe; }
From source file:de.sub.goobi.helper.ldap.Ldap.java
/** * Check if connection with login and password possible. * * @param inBenutzer//from w w w .j av a 2 s.c o m * User object * @param inPasswort * String * @return Login correct or not */ public boolean isUserPasswordCorrect(User inBenutzer, String inPasswort) { logger.debug("start login session with ldap"); Hashtable<String, String> env = getLdapConnectionSettings(); // Start TLS if (ConfigCore.getBooleanParameter("ldap_useTLS", false)) { logger.debug("use TLS for auth"); env = new Hashtable<>(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, ConfigCore.getParameter("ldap_url")); env.put("java.naming.ldap.version", "3"); LdapContext ctx = null; StartTlsResponse tls = null; try { ctx = new InitialLdapContext(env, null); // Authentication must be performed over a secure channel tls = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest()); tls.negotiate(); // Authenticate via SASL EXTERNAL mechanism using client X.509 // certificate contained in JVM keystore ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple"); ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, getUserDN(inBenutzer)); ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, inPasswort); ctx.reconnect(null); return true; // Perform search for privileged attributes under authenticated // context } catch (IOException e) { logger.error("TLS negotiation error:", e); return false; } catch (NamingException e) { logger.error("JNDI error:", e); return false; } finally { if (tls != null) { try { // Tear down TLS connection tls.close(); } catch (IOException e) { logger.error(e); } } if (ctx != null) { try { // Close LDAP connection ctx.close(); } catch (NamingException e) { logger.error(e); } } } } else { logger.debug("don't use TLS for auth"); if (ConfigCore.getBooleanParameter("useSimpleAuthentification", false)) { env.put(Context.SECURITY_AUTHENTICATION, "none"); // TODO auf passwort testen } else { env.put(Context.SECURITY_PRINCIPAL, getUserDN(inBenutzer)); env.put(Context.SECURITY_CREDENTIALS, inPasswort); } logger.debug("ldap environment set"); try { if (logger.isDebugEnabled()) { logger.debug("start classic ldap authentification"); logger.debug("user DN is " + getUserDN(inBenutzer)); } if (ConfigCore.getParameter("ldap_AttributeToTest") == null) { logger.debug("ldap attribute to test is null"); DirContext ctx = new InitialDirContext(env); ctx.close(); return true; } else { logger.debug("ldap attribute to test is not null"); DirContext ctx = new InitialDirContext(env); Attributes attrs = ctx.getAttributes(getUserDN(inBenutzer)); Attribute la = attrs.get(ConfigCore.getParameter("ldap_AttributeToTest")); logger.debug("ldap attributes set"); String test = (String) la.get(0); if (test.equals(ConfigCore.getParameter("ldap_ValueOfAttribute"))) { logger.debug("ldap ok"); ctx.close(); return true; } else { logger.debug("ldap not ok"); ctx.close(); return false; } } } catch (NamingException e) { if (logger.isDebugEnabled()) { logger.debug("login not allowed for " + inBenutzer.getLogin(), e); } return false; } } }
From source file:org.apache.directory.server.core.jndi.ObjStateFactoryIT.java
@Test public void testObjectFactory() throws Exception { LdifEntry akarasulu = getUserAddLdif(); getService().getAdminSession().add(new DefaultEntry(getService().getSchemaManager(), akarasulu.getEntry())); LdapContext sysRoot = getSystemContext(getService()); sysRoot.addToEnvironment(Context.OBJECT_FACTORIES, PersonObjectFactory.class.getName()); Object obj = sysRoot.lookup("uid=akarasulu, ou=users"); Attributes attrs = sysRoot.getAttributes("uid=akarasulu, ou=users"); assertEquals(Person.class, obj.getClass()); Person me = (Person) obj;/*from w ww . j ava 2s .c om*/ assertEquals(attrs.get("sn").get(), me.getLastname()); assertEquals(attrs.get("cn").get(), me.getCn()); assertTrue(ArrayUtils.isEquals(attrs.get("userPassword").get(), Strings.getBytesUtf8("test"))); assertEquals(attrs.get("telephonenumber").get(), me.getTelephoneNumber()); assertNull(me.getSeealso()); assertNull(me.getDescription()); }
From source file:org.apache.directory.server.core.jndi.ObjStateFactoryIT.java
@Test public void testStateFactory() throws Exception { LdapContext sysRoot = getSystemContext(getService()); sysRoot.addToEnvironment(Context.STATE_FACTORIES, PersonStateFactory.class.getName()); Person p = new Person("Rodriguez", "Mr. Kerberos", "noices", "555-1212", "sn=erodriguez", "committer"); sysRoot.bind("sn=Rodriguez, ou=users", p); Attributes attrs = sysRoot.getAttributes("sn=Rodriguez, ou=users"); assertEquals("Rodriguez", attrs.get("sn").get()); assertEquals("Mr. Kerberos", attrs.get("cn").get()); assertTrue(ArrayUtils.isEquals(attrs.get("userPassword").get(), Strings.getBytesUtf8("noices"))); assertEquals("555-1212", attrs.get("telephonenumber").get()); assertEquals("sn=erodriguez", attrs.get("seealso").get()); assertEquals("committer", attrs.get("description").get()); }
From source file:org.apache.directory.studio.connection.core.io.jndi.JNDIConnectionWrapper.java
/** * Search./* w w w . j ava 2s . c o m*/ * * @param searchBase the search base * @param filter the filter * @param searchControls the controls * @param aliasesDereferencingMethod the aliases dereferencing method * @param referralsHandlingMethod the referrals handling method * @param controls the LDAP controls * @param monitor the progress monitor * @param referralsInfo the referrals info * * @return the naming enumeration or null if an exception occurs. */ public JndiStudioNamingEnumeration search(final String searchBase, final String filter, final SearchControls searchControls, final AliasDereferencingMethod aliasesDereferencingMethod, final ReferralHandlingMethod referralsHandlingMethod, final Control[] controls, final StudioProgressMonitor monitor, final ReferralsInfo referralsInfo) { final long requestNum = searchRequestNum++; // start InnerRunnable runnable = new InnerRunnable() { public void run() { LdapContext searchCtx = context; try { // create the search context searchCtx = context.newInstance(controls); // translate alias dereferencing method searchCtx.addToEnvironment(JAVA_NAMING_LDAP_DEREF_ALIASES, translateDerefAliasMethod(aliasesDereferencingMethod)); // use "throw" as we handle referrals manually searchCtx.addToEnvironment(Context.REFERRAL, REFERRAL_THROW); // perform the search NamingEnumeration<SearchResult> result = searchCtx .search(JNDIConnectionWrapper.getSaveJndiName(searchBase), filter, searchControls); namingEnumeration = new JndiStudioNamingEnumeration(connection, searchCtx, result, null, searchBase, filter, searchControls, aliasesDereferencingMethod, referralsHandlingMethod, controls, requestNum, monitor, referralsInfo); } catch (PartialResultException | ReferralException e) { namingEnumeration = new JndiStudioNamingEnumeration(connection, searchCtx, null, e, searchBase, filter, searchControls, aliasesDereferencingMethod, referralsHandlingMethod, controls, requestNum, monitor, referralsInfo); } catch (NamingException e) { namingException = e; } for (IJndiLogger logger : getJndiLoggers()) { if (namingEnumeration != null) { logger.logSearchRequest(connection, searchBase, filter, searchControls, aliasesDereferencingMethod, controls, requestNum, namingException); } else { logger.logSearchRequest(connection, searchBase, filter, searchControls, aliasesDereferencingMethod, controls, requestNum, namingException); logger.logSearchResultDone(connection, 0, requestNum, namingException); } } } }; try { checkConnectionAndRunAndMonitor(runnable, monitor); } catch (NamingException ne) { monitor.reportError(ne); return null; } if (runnable.isCanceled()) { monitor.setCanceled(true); } if (runnable.getException() != null) { monitor.reportError(runnable.getException()); return null; } else { return runnable.getResult(); } }
From source file:org.apache.directory.studio.connection.core.io.jndi.JNDIConnectionWrapper.java
/** * Modifies attributes of an entry./* w w w .j a v a2 s. com*/ * * @param dn the Dn * @param modificationItems the modification items * @param controls the controls * @param monitor the progress monitor * @param referralsInfo the referrals info */ public void modifyEntry(final String dn, final ModificationItem[] modificationItems, final Control[] controls, final StudioProgressMonitor monitor, final ReferralsInfo referralsInfo) { if (connection.isReadOnly()) { monitor.reportError( new Exception(NLS.bind(Messages.error__connection_is_readonly, connection.getName()))); return; } InnerRunnable runnable = new InnerRunnable() { public void run() { try { // create modify context LdapContext modCtx = context.newInstance(controls); // use "throw" as we handle referrals manually modCtx.addToEnvironment(Context.REFERRAL, REFERRAL_THROW); // perform modification modCtx.modifyAttributes(getSaveJndiName(dn), modificationItems); } catch (ReferralException re) { try { ReferralsInfo newReferralsInfo = handleReferralException(re, referralsInfo); Referral referral = newReferralsInfo.getNextReferral(); if (referral != null) { Connection referralConnection = ConnectionWrapperUtils.getReferralConnection(referral, monitor, this); if (referralConnection != null) { List<String> urls = new ArrayList<>(referral.getLdapUrls()); String referralDn = new LdapUrl(urls.get(0)).getDn().getName(); referralConnection.getConnectionWrapper().modifyEntry(referralDn, modificationItems, controls, monitor, newReferralsInfo); } else { canceled = true; } } return; } catch (NamingException ne) { namingException = ne; } catch (LdapURLEncodingException e) { namingException = new NamingException(e.getMessage()); } } catch (NamingException ne) { namingException = ne; } for (IJndiLogger logger : getJndiLoggers()) { logger.logChangetypeModify(connection, dn, modificationItems, controls, namingException); } } }; try { checkConnectionAndRunAndMonitor(runnable, monitor); } catch (NamingException ne) { monitor.reportError(ne); } if (runnable.isCanceled()) { monitor.setCanceled(true); } if (runnable.getException() != null) { monitor.reportError(runnable.getException()); } }
From source file:org.apache.directory.studio.connection.core.io.jndi.JNDIConnectionWrapper.java
/** * Renames an entry.//from www.jav a 2s . c om * * @param oldDn the old Dn * @param newDn the new Dn * @param deleteOldRdn true to delete the old Rdn * @param controls the controls * @param monitor the progress monitor * @param referralsInfo the referrals info */ public void renameEntry(final String oldDn, final String newDn, final boolean deleteOldRdn, final Control[] controls, final StudioProgressMonitor monitor, final ReferralsInfo referralsInfo) { if (connection.isReadOnly()) { monitor.reportError( new Exception(NLS.bind(Messages.error__connection_is_readonly, connection.getName()))); return; } InnerRunnable runnable = new InnerRunnable() { public void run() { try { // create modify context LdapContext modCtx = context.newInstance(controls); // use "throw" as we handle referrals manually modCtx.addToEnvironment(Context.REFERRAL, REFERRAL_THROW); // delete old Rdn if (deleteOldRdn) { modCtx.addToEnvironment(JAVA_NAMING_LDAP_DELETE_RDN, "true"); //$NON-NLS-1$ } else { modCtx.addToEnvironment(JAVA_NAMING_LDAP_DELETE_RDN, "false"); //$NON-NLS-1$ } // rename entry modCtx.rename(getSaveJndiName(oldDn), getSaveJndiName(newDn)); } catch (ReferralException re) { try { ReferralsInfo newReferralsInfo = handleReferralException(re, referralsInfo); Referral referral = newReferralsInfo.getNextReferral(); if (referral != null) { Connection referralConnection = ConnectionWrapperUtils.getReferralConnection(referral, monitor, this); if (referralConnection != null) { referralConnection.getConnectionWrapper().renameEntry(oldDn, newDn, deleteOldRdn, controls, monitor, newReferralsInfo); } else { canceled = true; } } } catch (NamingException ne) { namingException = ne; } } catch (NamingException ne) { namingException = ne; } for (IJndiLogger logger : getJndiLoggers()) { logger.logChangetypeModDn(connection, oldDn, newDn, deleteOldRdn, controls, namingException); } } }; try { checkConnectionAndRunAndMonitor(runnable, monitor); } catch (NamingException ne) { monitor.reportError(ne); } if (runnable.isCanceled()) { monitor.setCanceled(true); } if (runnable.getException() != null) { monitor.reportError(runnable.getException()); } }
From source file:org.apache.directory.studio.connection.core.io.jndi.JNDIConnectionWrapper.java
/** * Creates an entry.// w ww . j a v a 2s .c o m * * @param dn the entry's Dn * @param attributes the entry's attributes * @param controls the controls * @param monitor the progress monitor * @param referralsInfo the referrals info */ public void createEntry(final String dn, final Attributes attributes, final Control[] controls, final StudioProgressMonitor monitor, final ReferralsInfo referralsInfo) { if (connection.isReadOnly()) { monitor.reportError( new Exception(NLS.bind(Messages.error__connection_is_readonly, connection.getName()))); return; } InnerRunnable runnable = new InnerRunnable() { public void run() { try { // create modify context LdapContext modCtx = context.newInstance(controls); // use "throw" as we handle referrals manually modCtx.addToEnvironment(Context.REFERRAL, REFERRAL_THROW); // create entry modCtx.createSubcontext(getSaveJndiName(dn), attributes); } catch (ReferralException re) { try { ReferralsInfo newReferralsInfo = handleReferralException(re, referralsInfo); Referral referral = newReferralsInfo.getNextReferral(); if (referral != null) { Connection referralConnection = ConnectionWrapperUtils.getReferralConnection(referral, monitor, this); if (referralConnection != null) { List<String> urls = new ArrayList<>(referral.getLdapUrls()); String referralDn = new LdapUrl(urls.get(0)).getDn().getName(); referralConnection.getConnectionWrapper().createEntry(referralDn, attributes, controls, monitor, newReferralsInfo); } else { canceled = true; } } } catch (NamingException ne) { namingException = ne; } catch (LdapURLEncodingException e) { namingException = new NamingException(e.getMessage()); } } catch (NamingException ne) { namingException = ne; } for (IJndiLogger logger : getJndiLoggers()) { logger.logChangetypeAdd(connection, dn, attributes, controls, namingException); } } }; try { checkConnectionAndRunAndMonitor(runnable, monitor); } catch (NamingException ne) { monitor.reportError(ne); } if (runnable.isCanceled()) { monitor.setCanceled(true); } if (runnable.getException() != null) { monitor.reportError(runnable.getException()); } }
From source file:org.apache.directory.studio.connection.core.io.jndi.JNDIConnectionWrapper.java
/** * Deletes an entry./* w w w . j av a 2s. co m*/ * * @param dn the Dn of the entry to delete * @param controls the controls * @param monitor the progress monitor * @param referralsInfo the referrals info */ public void deleteEntry(final String dn, final Control[] controls, final StudioProgressMonitor monitor, final ReferralsInfo referralsInfo) { if (connection.isReadOnly()) { monitor.reportError( new Exception(NLS.bind(Messages.error__connection_is_readonly, connection.getName()))); return; } InnerRunnable runnable = new InnerRunnable() { public void run() { try { // create modify context LdapContext modCtx = context.newInstance(controls); // use "throw" as we handle referrals manually modCtx.addToEnvironment(Context.REFERRAL, REFERRAL_THROW); // delete entry modCtx.destroySubcontext(getSaveJndiName(dn)); } catch (ReferralException re) { try { ReferralsInfo newReferralsInfo = handleReferralException(re, referralsInfo); Referral referral = newReferralsInfo.getNextReferral(); if (referral != null) { Connection referralConnection = ConnectionWrapperUtils.getReferralConnection(referral, monitor, this); if (referralConnection != null) { List<String> urls = new ArrayList<>(referral.getLdapUrls()); String referralDn = new LdapUrl(urls.get(0)).getDn().getName(); referralConnection.getConnectionWrapper().deleteEntry(referralDn, controls, monitor, newReferralsInfo); } else { canceled = true; } } } catch (NamingException ne) { namingException = ne; } catch (LdapURLEncodingException e) { namingException = new NamingException(e.getMessage()); } } catch (NamingException ne) { namingException = ne; } for (IJndiLogger logger : getJndiLoggers()) { logger.logChangetypeDelete(connection, dn, controls, namingException); } } }; try { checkConnectionAndRunAndMonitor(runnable, monitor); } catch (NamingException ne) { monitor.reportError(ne); } if (runnable.isCanceled()) { monitor.setCanceled(true); } if (runnable.getException() != null) { monitor.reportError(runnable.getException()); } }