List of usage examples for javax.naming.directory InitialDirContext InitialDirContext
public InitialDirContext(Hashtable<?, ?> environment) throws NamingException
From source file:org.apache.directory.server.operations.bind.MiscBindIT.java
/** * Test to make sure anonymous binds are allowed on the RootDSE even when disabled * in general when going through the wire protocol. * * @throws Exception if anything goes wrong *///from w ww . j a v a 2 s . co m @Test public void testEnableAnonymousBindsOnRootDse() throws Exception { getLdapServer().getDirectoryService().setAllowAnonymousAccess(true); // Use the SUN JNDI provider to hit server port and bind as anonymous Hashtable<String, Object> env = new Hashtable<String, Object>(); env.put(Context.PROVIDER_URL, Network.ldapLoopbackUrl(getLdapServer().getPort())); env.put(Context.SECURITY_AUTHENTICATION, "none"); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); InitialDirContext ctx = new InitialDirContext(env); SearchControls cons = new SearchControls(); cons.setSearchScope(SearchControls.OBJECT_SCOPE); NamingEnumeration<SearchResult> list = ctx.search("", "(objectClass=*)", cons); SearchResult result = null; if (list.hasMore()) { result = list.next(); } assertFalse(list.hasMore()); list.close(); assertNotNull(result); assertEquals("", result.getName().trim()); }
From source file:com.alfaariss.oa.engine.attribute.gather.processor.jndi.JNDIGatherer.java
/** * Starts the object.// ww w . j a va 2s . c om * <br> * Reads its configuration and tests the JNDI connection. * @see IProcessor#start(IConfigurationManager, org.w3c.dom.Element) */ public void start(IConfigurationManager oConfigurationManager, Element eConfig) throws AttributeException { try { _bEnabled = true; String sEnabled = oConfigurationManager.getParam(eConfig, "enabled"); if (sEnabled != null) { if (sEnabled.equalsIgnoreCase("FALSE")) _bEnabled = false; else if (!sEnabled.equalsIgnoreCase("TRUE")) { _logger.error("Unknown value in 'enabled' configuration item: " + sEnabled); throw new AttributeException(SystemErrors.ERROR_CONFIG_READ); } } if (!_bEnabled) return; //object is disabled, so why should I bother to load its configuration? _sID = oConfigurationManager.getParam(eConfig, "id"); if (_sID == null) { _logger.error("No 'id' item found in configuration"); throw new AttributeException(SystemErrors.ERROR_CONFIG_READ); } _sFriendlyName = oConfigurationManager.getParam(eConfig, "friendlyname"); if (_sFriendlyName == null) { _logger.error("No 'friendlyname' item found in configuration"); throw new AttributeException(SystemErrors.ERROR_CONFIG_READ); } Element eResource = oConfigurationManager.getSection(eConfig, "resource"); if (eResource == null) { _logger.error("No 'resource' section found in configuration"); throw new AttributeException(SystemErrors.ERROR_CONFIG_READ); } Element eDN = oConfigurationManager.getSection(eResource, "dn"); if (eDN == null) { _logger.error("No 'dn' section found in 'resource' section in configuration"); throw new AttributeException(SystemErrors.ERROR_CONFIG_READ); } _sDNBase = oConfigurationManager.getParam(eDN, "base"); if (_sDNBase == null) { _logger.error("No 'dn' item found in 'base' section in configuration"); throw new AttributeException(SystemErrors.ERROR_CONFIG_READ); } _sDNUser = oConfigurationManager.getParam(eDN, "user"); _sFilter = oConfigurationManager.getParam(eDN, "filter"); if (_sFilter != null && _sDNUser != null) { _logger.error( "Invalid configuration: Both 'user' and 'filter' item found in 'base' section in configuration"); throw new AttributeException(SystemErrors.ERROR_CONFIG_READ); } else if (_sFilter != null) { _logger.info("Using search filter: " + _sFilter); } else if (_sDNUser != null) { _logger.info("Generating search filter with user: " + _sDNUser); } else { _logger.error("No 'user' or 'filter' item found in 'base' section in configuration"); throw new AttributeException(SystemErrors.ERROR_CONFIG_READ); } Element eGather = oConfigurationManager.getSection(eConfig, "gather"); if (eGather == null) _logger.info("No optional 'gather' section found in configuration"); else { Element eAttribute = oConfigurationManager.getSection(eGather, "attribute"); while (eAttribute != null) { String sName = oConfigurationManager.getParam(eAttribute, "name"); if (sName == null) { _logger.error("No 'name' item found in 'attribute' section"); throw new AttributeException(SystemErrors.ERROR_CONFIG_READ); } if (sName.trim().length() == 0) { _logger.error("Empty 'name' item found in 'attribute' section"); throw new AttributeException(SystemErrors.ERROR_INIT); } if (_listGather.contains(sName)) { _logger.error("Attribute name not unique: " + sName); throw new AttributeException(SystemErrors.ERROR_INIT); } _listGather.add(sName); eAttribute = oConfigurationManager.getNextSection(eAttribute); } _logger.info("Configured to gather only the following subset: " + _listGather.toString()); } _htJNDIEnvironment = readJNDIContext(oConfigurationManager, eResource); //test connection new InitialDirContext(_htJNDIEnvironment); Element eMapper = oConfigurationManager.getSection(eConfig, "mapper"); if (eMapper == null) _logger.info("No optional 'mapper' section found in configuration"); else { Element eMap = oConfigurationManager.getSection(eMapper, "map"); while (eMap != null) { String sExt = oConfigurationManager.getParam(eMap, "ext"); if (sExt == null) { _logger.error("No 'ext' item found in 'map' section"); throw new AttributeException(SystemErrors.ERROR_CONFIG_READ); } String sInt = oConfigurationManager.getParam(eMap, "int"); if (sInt == null) { _logger.error("No 'int' item found in 'map' section"); throw new AttributeException(SystemErrors.ERROR_CONFIG_READ); } if (_htMapper.containsKey(sExt)) { _logger.error("Ext name not unique in map with 'ext' value: " + sExt); throw new AttributeException(SystemErrors.ERROR_INIT); } if (_htMapper.contains(sInt)) { _logger.error("Int name not unique in map with 'int' value: " + sInt); throw new AttributeException(SystemErrors.ERROR_INIT); } _htMapper.put(sExt, sInt); eMap = oConfigurationManager.getNextSection(eMap); } } _logger.info("Started: JDNI Attribute Gatherer"); } catch (AttributeException e) { throw e; } catch (Exception e) { _logger.fatal("Could not initialize object", e); throw new AttributeException(SystemErrors.ERROR_INTERNAL); } }
From source file:org.springframework.ldap.samples.article.dao.TraditionalPersonDaoImpl.java
private DirContext createContext(Hashtable env) { env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); String tempUrl = createUrl(); env.put(Context.PROVIDER_URL, tempUrl); DirContext ctx;/* ww w . j a va2 s . c o m*/ try { ctx = new InitialDirContext(env); } catch (NamingException e) { throw new RuntimeException(e); } return ctx; }
From source file:org.openadaptor.auxil.connector.jndi.JNDIConnection.java
/** * Connect to a JNDI Service./*from ww w . j a va 2s.c om*/ * * @return DirContext obtained. * @throws NamingException */ public DirContext connect() throws NamingException { return new InitialDirContext(getConnectionProperties()); }
From source file:org.springframework.ldap.demo.dao.PersonDaoImpl.java
private DirContext createContext(Hashtable<String, String> env) { env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); String tempUrl = createUrl(); env.put(Context.PROVIDER_URL, tempUrl); DirContext ctx;// ww w.j a va 2 s . c o m try { ctx = new InitialDirContext(env); } catch (NamingException e) { throw new RuntimeException(e); } return ctx; }
From source file:de.sub.goobi.helper.ldap.Ldap.java
/** * Check if connection with login and password possible. * * @param inBenutzer//from w ww . j a va2 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:com.alfaariss.oa.engine.user.provisioning.storage.external.jndi.JNDIExternalStorage.java
/** * Returns the field value of the specified field for the specified id. * @see IExternalStorage#getField(java.lang.String, java.lang.String) *//* w w w .ja v a 2s .c o m*/ public Object getField(String id, String field) throws UserException { DirContext oDirContext = null; NamingEnumeration oNamingEnumeration = null; Object oValue = null; try { try { oDirContext = new InitialDirContext(_htJNDIEnvironment); } catch (NamingException e) { _logger.error("Could not create the connection: " + _htJNDIEnvironment); throw new UserException(SystemErrors.ERROR_RESOURCE_CONNECT, e); } SearchControls oScope = new SearchControls(); oScope.setSearchScope(SearchControls.SUBTREE_SCOPE); String searchFilter = resolveSearchQuery(id); try { oNamingEnumeration = oDirContext.search(_sDNBase, searchFilter, oScope); } catch (InvalidSearchFilterException e) { StringBuffer sbFailed = new StringBuffer("Wrong filter: "); sbFailed.append(searchFilter); sbFailed.append(" while searching for attribute '"); sbFailed.append(field); sbFailed.append("' for id: "); sbFailed.append(id); _logger.error(sbFailed.toString(), e); throw new UserException(SystemErrors.ERROR_INTERNAL, e); } catch (NamingException e) { _logger.error("User unknown: " + id); throw new UserException(SystemErrors.ERROR_RESOURCE_RETRIEVE, e); } if (!oNamingEnumeration.hasMore()) { StringBuffer sbFailed = new StringBuffer("User with id '"); sbFailed.append(id); sbFailed.append("' not found after LDAP search with filter: "); sbFailed.append(searchFilter); _logger.error(sbFailed.toString()); throw new UserException(SystemErrors.ERROR_RESOURCE_RETRIEVE); } SearchResult oSearchResult = (SearchResult) oNamingEnumeration.next(); Attributes oAttributes = oSearchResult.getAttributes(); NamingEnumeration oAttrEnum = oAttributes.getAll(); if (oAttrEnum.hasMore()) { Attribute oAttribute = (Attribute) oAttrEnum.next(); oValue = oAttribute.get(); } } catch (UserException e) { throw e; } catch (Exception e) { _logger.error("Could not retrieve field: " + field, e); throw new UserException(SystemErrors.ERROR_INTERNAL, e); } finally { if (oNamingEnumeration != null) { try { oNamingEnumeration.close(); } catch (Exception e) { _logger.error("Could not close Naming Enumeration after searching for user with id: " + id, e); } } if (oDirContext != null) { try { oDirContext.close(); } catch (NamingException e) { _logger.error("Could not close Dir Context after searching for user with id: " + id, e); } } } return oValue; }
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.j a va2s. c om 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:gov.medicaid.dao.impl.LDAPIdentityProviderDAOBean.java
/** * Removes the user from the underlying identity provider. * * @param username this is the user that will be permanently removed * @throws PortalServiceException for any errors encountered */// w ww. j a v a2 s.c o m public void removeUser(String username) throws PortalServiceException { DirContext ctx = null; try { ctx = new InitialDirContext(env); List<String> roles = findRoles(username); for (String existingRole : roles) { removeRoleAssignment(ctx, username, existingRole); } ctx.unbind(MessageFormat.format(userDNPattern, username)); } catch (NamingException e) { throw new PortalServiceConfigurationException("Unable to get groups.", e); } finally { closeContext(ctx); } }
From source file:org.alfresco.repo.security.authentication.ldap.LDAPInitialDirContextFactoryImpl.java
private InitialDirContext buildInitialDirContext(Hashtable<String, String> env, int pageSize, AuthenticationDiagnostic diagnostic) throws AuthenticationException { String securityPrincipal = env.get(Context.SECURITY_PRINCIPAL); String providerURL = env.get(Context.PROVIDER_URL); if (isSSLSocketFactoryRequired()) { KeyStore trustStore = initTrustStore(); AlfrescoSSLSocketFactory.initTrustedSSLSocketFactory(trustStore); env.put("java.naming.ldap.factory.socket", AlfrescoSSLSocketFactory.class.getName()); }/* www .j ava 2s . com*/ if (diagnostic == null) { diagnostic = new AuthenticationDiagnostic(); } try { // If a page size has been requested, use LDAP v3 paging if (pageSize > 0) { InitialLdapContext ctx = new InitialLdapContext(env, null); ctx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.CRITICAL) }); return ctx; } else { InitialDirContext ret = new InitialDirContext(env); Object[] args = { providerURL, securityPrincipal }; diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTED, true, args); return ret; } } catch (javax.naming.AuthenticationException ax) { Object[] args1 = { securityPrincipal }; Object[] args = { providerURL, securityPrincipal }; diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTED, true, args); diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_AUTHENTICATION, false, args1); // wrong user/password - if we get this far the connection is O.K Object[] args2 = { securityPrincipal, ax.getLocalizedMessage() }; throw new AuthenticationException("authentication.err.authentication", diagnostic, args2, ax); } catch (CommunicationException ce) { Object[] args1 = { providerURL }; diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTING, false, args1); StringBuffer message = new StringBuffer(); message.append(ce.getClass().getName() + ", " + ce.getMessage()); Throwable cause = ce.getCause(); while (cause != null) { message.append(", "); message.append(cause.getClass().getName() + ", " + cause.getMessage()); cause = cause.getCause(); } // failed to connect Object[] args = { providerURL, message.toString() }; throw new AuthenticationException("authentication.err.communication", diagnostic, args, cause); } catch (NamingException nx) { Object[] args = { providerURL }; diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTING, false, args); StringBuffer message = new StringBuffer(); message.append(nx.getClass().getName() + ", " + nx.getMessage()); Throwable cause = nx.getCause(); while (cause != null) { message.append(", "); message.append(cause.getClass().getName() + ", " + cause.getMessage()); cause = cause.getCause(); } // failed to connect Object[] args1 = { providerURL, message.toString() }; throw new AuthenticationException("authentication.err.connection", diagnostic, args1, nx); } catch (IOException e) { Object[] args = { providerURL, securityPrincipal }; diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTED, true, args); throw new AuthenticationException("Unable to encode LDAP v3 request controls", e); } }