List of usage examples for javax.naming.ldap InitialLdapContext InitialLdapContext
@SuppressWarnings("unchecked") public InitialLdapContext(Hashtable<?, ?> environment, Control[] connCtls) throws NamingException
From source file:nl.nn.adapterframework.webcontrol.LoginFilter.java
private boolean checkUsernamePassword(String username, String password, String authorizePathMode) { String dnUser = Misc.replace(ldapAuthUserBase, "%UID%", username); Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, ldapAuthUrl); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, dnUser); env.put(Context.SECURITY_CREDENTIALS, password); DirContext ctx = null;/*from w w w . j av a 2 s .c o m*/ try { try { ctx = new InitialDirContext(env); } catch (CommunicationException e) { log.info("cannot create constructor for DirContext (" + e.getMessage() + "], will try again with dummy SocketFactory"); env.put("java.naming.ldap.factory.socket", DummySSLSocketFactory.class.getName()); ctx = new InitialLdapContext(env, null); } if (authorizePathMode == null) { return true; } else { if (authorizePathMode.equals(AUTH_PATH_MODE_OBSERVER)) { if (isMemberOf(ctx, dnUser, ldapAuthObserverBase)) { return true; } if (isMemberOf(ctx, dnUser, ldapAuthDataAdminBase)) { return true; } } if (authorizePathMode.equals(AUTH_PATH_MODE_DATAADMIN)) { if (isMemberOf(ctx, dnUser, ldapAuthDataAdminBase)) { return true; } } if (authorizePathMode.equals(AUTH_PATH_MODE_TESTER)) { if (isMemberOf(ctx, dnUser, ldapAuthTesterBase)) { return true; } } } } catch (AuthenticationException e) { return false; } catch (Exception e) { log.warn("LoginFilter caught Exception", e); return false; } finally { if (ctx != null) { try { ctx.close(); } catch (Exception e) { log.warn("LoginFilter caught Exception", e); } } } return false; }
From source file:no.feide.moria.directory.backend.JNDIBackend.java
/** * Creates a new connection to a given backend provider URL. * @param url//from w ww . j a v a2s . c o m * The backend provider URL. * @return The opened backend connection. * @throws NamingException * If unable to connect to the provider given by * <code>url</code>. */ private InitialLdapContext connect(final String url) throws NamingException { // Prepare connection. Hashtable<String, String> env = new Hashtable<String, String>(defaultEnv); env.put(Context.PROVIDER_URL, url); return new InitialLdapContext(env, null); }
From source file:ome.logic.LdapImpl.java
/** * Creates the initial context with no connection request controls in order * to check authentication. If authentication fails, this method throws * a {@link SecurityViolation}.//from w w w.ja va2s . c om * * @return {@link javax.naming.ldap.LdapContext} */ @SuppressWarnings("unchecked") private void isAuthContext(String username, String password) { Hashtable<String, String> env = new Hashtable<String, String>(5, 0.75f); try { env = (Hashtable<String, String>) ctx.getReadOnlyContext().getEnvironment(); if (username != null && !username.equals("")) { env.put(Context.SECURITY_PRINCIPAL, username); if (password != null) { env.put(Context.SECURITY_CREDENTIALS, password); } } new InitialLdapContext(env, null); } catch (AuthenticationException authEx) { throw new SecurityViolation("Authentication falilure! " + authEx.toString()); } catch (NamingException e) { throw new SecurityViolation("Naming exception! " + e.toString()); } }
From source file:org.acegisecurity.ldap.DefaultInitialDirContextFactory.java
private InitialDirContext connect(Hashtable env) { if (logger.isDebugEnabled()) { Hashtable envClone = (Hashtable) env.clone(); if (envClone.containsKey(Context.SECURITY_CREDENTIALS)) { envClone.put(Context.SECURITY_CREDENTIALS, "******"); }//from w w w. j av a 2 s . c om logger.debug("Creating InitialDirContext with environment " + envClone); } try { return useLdapContext ? new InitialLdapContext(env, null) : new InitialDirContext(env); } catch (NamingException ne) { if ((ne instanceof javax.naming.AuthenticationException) || (ne instanceof OperationNotSupportedException)) { throw new BadCredentialsException( messages.getMessage("DefaultIntitalDirContextFactory.badCredentials", "Bad credentials"), ne); } if (ne instanceof CommunicationException) { throw new LdapDataAccessException( messages.getMessage("DefaultIntitalDirContextFactory.communicationFailure", "Unable to connect to LDAP server"), ne); } throw new LdapDataAccessException( messages.getMessage("DefaultIntitalDirContextFactory.unexpectedException", "Failed to obtain InitialDirContext due to unexpected exception"), ne); } }
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()); }/* ww w . j a v a2 s . co m*/ 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); } }
From source file:org.apache.ambari.server.serveraction.kerberos.ADKerberosOperationHandler.java
/** * Helper method to create the LDAP context needed to interact with the Active Directory. * <p/>//w ww .j ava 2s . c o m * This is mainly used to help with building mocks for test cases. * * @param properties environment used to create the initial DirContext. * Null indicates an empty environment. * @param controls connection request controls for the initial context. * If null, no connection request controls are used. * @return the relevant LdapContext * @throws NamingException if a naming exception is encountered */ protected LdapContext createInitialLdapContext(Properties properties, Control[] controls) throws NamingException { return new InitialLdapContext(properties, controls); }
From source file:org.apache.cloudstack.ldap.LdapContextFactory.java
private LdapContext createInitialDirContext(final String principal, final String password, final String providerUrl, final boolean isSystemContext, Long domainId) throws NamingException, IOException { Hashtable<String, String> environment = getEnvironment(principal, password, providerUrl, isSystemContext, domainId);/*w ww.java2s . com*/ s_logger.debug("initializing ldap with provider url: " + environment.get(Context.PROVIDER_URL)); return new InitialLdapContext(environment, null); }
From source file:org.apache.directory.server.ldap.handlers.sasl.AbstractSaslCallbackHandler.java
/** * Convenience method for acquiring an {@link LdapContext} for the client to use for the * duration of a session.// w w w.j a v a 2 s .com * * @param session The current session. * @param bindRequest The current BindRequest. * @param env An environment to be used to acquire an {@link LdapContext}. * @return An {@link LdapContext} for the client. */ protected LdapContext getContext(IoSession session, BindRequest bindRequest, Hashtable<String, Object> env) { LdapResult result = bindRequest.getResultResponse().getLdapResult(); LdapContext ctx = null; try { Control[] connCtls = bindRequest.getControls().values().toArray(EMPTY); env.put(DirectoryService.JNDI_KEY, directoryService); ctx = new InitialLdapContext(env, JndiUtils.toJndiControls(directoryService.getLdapCodecService(), connCtls)); } catch (Exception e) { ResultCodeEnum code; Dn dn = null; if (e instanceof LdapOperationException) { code = ((LdapOperationException) e).getResultCode(); result.setResultCode(code); dn = ((LdapOperationException) e).getResolvedDn(); } else { code = ResultCodeEnum.getBestEstimate(e, bindRequest.getType()); result.setResultCode(code); } String msg = "Bind failed: " + e.getLocalizedMessage(); if (LOG.isDebugEnabled()) { msg += ":\n" + ExceptionUtils.getStackTrace(e); msg += "\n\nBindRequest = \n" + bindRequest.toString(); } if ((dn != null) && ((code == ResultCodeEnum.NO_SUCH_OBJECT) || (code == ResultCodeEnum.ALIAS_PROBLEM) || (code == ResultCodeEnum.INVALID_DN_SYNTAX) || (code == ResultCodeEnum.ALIAS_DEREFERENCING_PROBLEM))) { result.setMatchedDn(dn); } result.setDiagnosticMessage(msg); session.write(bindRequest.getResultResponse()); ctx = null; } return ctx; }
From source file:org.apache.directory.server.operations.bind.MiscBindIT.java
@Test public void testFailureWithUnsupportedControl() throws Exception { Control unsupported = new OpaqueControl("1.1.1.1"); unsupported.setCritical(true);//ww w . j a va 2 s . c o m getLdapServer().getDirectoryService().setAllowAnonymousAccess(true); Hashtable<String, Object> env = new Hashtable<String, Object>(); env.put(Context.PROVIDER_URL, Network.ldapLoopbackUrl(getLdapServer().getPort()) + "/ou=system"); env.put("java.naming.ldap.version", "3"); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_CREDENTIALS, "secret"); env.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system"); InitialLdapContext ctx = new InitialLdapContext(env, null); Attributes user = new BasicAttributes("cn", "Kate Bush", true); Attribute oc = new BasicAttribute("objectClass"); oc.add("top"); oc.add("person"); oc.add("organizationalPerson"); oc.add("inetOrgPerson"); user.put(oc); user.put("sn", "Bush"); user.put("userPassword", "Aerial"); ctx.setRequestControls(JndiUtils.toJndiControls(getLdapServer().getDirectoryService().getLdapCodecService(), new Control[] { unsupported })); try { ctx.createSubcontext("cn=Kate Bush", user); fail(); } catch (OperationNotSupportedException e) { } unsupported.setCritical(false); ctx.setRequestControls(JndiUtils.toJndiControls(getLdapServer().getDirectoryService().getLdapCodecService(), new Control[] { unsupported })); DirContext kate = ctx.createSubcontext("cn=Kate Bush", user); assertNotNull(kate); assertTrue(ArrayUtils.isEquals(Asn1StringUtils.getBytesUtf8("Aerial"), kate.getAttributes("").get("userPassword").get())); ctx.destroySubcontext("cn=Kate Bush"); }
From source file:org.apache.directory.studio.connection.core.io.jndi.JNDIConnectionWrapper.java
private void doConnect(final StudioProgressMonitor monitor) throws NamingException { context = null;/*www .j a va2 s .c om*/ isConnected = true; // setup connection parameters String host = connection.getConnectionParameter().getHost(); int port = connection.getConnectionParameter().getPort(); long timeout = connection.getConnectionParameter().getTimeout(); useLdaps = connection.getConnectionParameter() .getEncryptionMethod() == ConnectionParameter.EncryptionMethod.LDAPS; useStartTLS = connection.getConnectionParameter() .getEncryptionMethod() == ConnectionParameter.EncryptionMethod.START_TLS; environment = new Hashtable<>(); Preferences preferences = ConnectionCorePlugin.getDefault().getPluginPreferences(); final boolean validateCertificates = preferences .getBoolean(ConnectionCoreConstants.PREFERENCE_VALIDATE_CERTIFICATES); String ldapCtxFactory = preferences.getString(ConnectionCoreConstants.PREFERENCE_LDAP_CONTEXT_FACTORY); environment.put(Context.INITIAL_CONTEXT_FACTORY, ldapCtxFactory); environment.put(JAVA_NAMING_LDAP_VERSION, "3"); //$NON-NLS-1$ // timeouts /* * Don't use a timeout when using ldaps: JNDI throws a SocketException when setting a timeout on SSL connections. * See https://bugs.openjdk.java.net/browse/JDK-8173451 */ if (!useLdaps) { if (timeout < 0) { timeout = 0; } environment.put(COM_SUN_JNDI_LDAP_CONNECT_TIMEOUT, Long.toString(timeout)); //$NON-NLS-1$ } environment.put(COM_SUN_JNDI_DNS_TIMEOUT_INITIAL, "2000"); //$NON-NLS-1$ environment.put(COM_SUN_JNDI_DNS_TIMEOUT_RETRIES, "3"); //$NON-NLS-1$ // ldaps:// if (useLdaps) { environment.put(Context.PROVIDER_URL, LdapUrl.LDAPS_SCHEME + host + ':' + port); environment.put(Context.SECURITY_PROTOCOL, "ssl"); //$NON-NLS-1$ // host name verification is done in StudioTrustManager environment.put(JAVA_NAMING_LDAP_FACTORY_SOCKET, validateCertificates ? StudioSSLSocketFactory.class.getName() : DummySSLSocketFactory.class.getName()); } else { environment.put(Context.PROVIDER_URL, LdapUrl.LDAP_SCHEME + host + ':' + port); } if (binaryAttributes != null) { setBinaryAttributes(binaryAttributes); } InnerRunnable runnable = new InnerRunnable() { public void run() { try { context = new InitialLdapContext(environment, null); if (useStartTLS) { try { StartTlsResponse tls = (StartTlsResponse) context .extendedOperation(new StartTlsRequest()); // deactivate host name verification at this level, // host name verification is done in StudioTrustManager tls.setHostnameVerifier((hostname, session) -> true); if (validateCertificates) { tls.negotiate(StudioSSLSocketFactory.getDefault()); } else { tls.negotiate(DummySSLSocketFactory.getDefault()); } } catch (Exception e) { namingException = new NamingException(e.getMessage() != null ? e.getMessage() : "Error while establishing TLS session"); //$NON-NLS-1$ namingException.setRootCause(e); context.close(); } } } catch (NamingException ne) { namingException = ne; } } }; runAndMonitor(runnable, monitor); if (runnable.getException() != null) { throw runnable.getException(); } else if (context != null) { // all OK } else { throw new NamingException("???"); //$NON-NLS-1$ } }