List of usage examples for javax.naming.ldap InitialLdapContext InitialLdapContext
@SuppressWarnings("unchecked") public InitialLdapContext(Hashtable<?, ?> environment, Control[] connCtls) throws NamingException
From source file:org.jsecurity.realm.ldap.DefaultLdapContextFactory.java
public LdapContext getLdapContext(String username, String password) throws NamingException { if (searchBase == null) { throw new IllegalStateException("A search base must be specified."); }//from w w w . j a va2 s. co m if (url == null) { throw new IllegalStateException("An LDAP URL must be specified of the form ldap://<hostname>:<port>"); } if (username != null && principalSuffix != null) { username += principalSuffix; } Hashtable<String, String> env = new Hashtable<String, String>(); env.put(Context.SECURITY_AUTHENTICATION, authentication); if (username != null) { env.put(Context.SECURITY_PRINCIPAL, username); } if (password != null) { env.put(Context.SECURITY_CREDENTIALS, password); } env.put(Context.INITIAL_CONTEXT_FACTORY, contextFactoryClassName); env.put(Context.PROVIDER_URL, url); env.put(Context.REFERRAL, referral); // Only pool connections for system contexts if (usePooling && username != null && username.equals(systemUsername)) { // Enable connection pooling env.put(SUN_CONNECTION_POOLING_PROPERTY, "true"); } if (additionalEnvironment != null) { env.putAll(additionalEnvironment); } if (log.isDebugEnabled()) { log.debug("Initializing LDAP context using URL [" + url + "] and username [" + systemUsername + "] " + "with pooling [" + (usePooling ? "enabled" : "disabled") + "]"); } return new InitialLdapContext(env, null); }
From source file:org.kitodo.production.services.data.LdapServerService.java
private URI getUserHomeDirectoryWithTLS(Hashtable<String, String> env, String userFolderBasePath, User user) { env.put("java.naming.ldap.version", "3"); LdapContext ctx = null;/*from w ww.ja v a2s . com*/ 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(); ctx.reconnect(null); Attributes attrs = ctx.getAttributes(buildUserDN(user)); Attribute la = attrs.get("homeDirectory"); return URI.create((String) la.get(0)); } catch (IOException e) { logger.error("TLS negotiation error:", e); return Paths.get(userFolderBasePath, user.getLogin()).toUri(); } catch (NamingException e) { logger.error("JNDI error:", e); return Paths.get(userFolderBasePath, user.getLogin()).toUri(); } finally { closeConnections(ctx, tls); } }
From source file:org.kitodo.production.services.data.LdapServerService.java
private boolean isPasswordCorrectForAuthWithTLS(Hashtable<String, String> env, User user, String password) { env.put("java.naming.ldap.version", "3"); LdapContext ctx = null;/*from w ww . j av a 2 s . co m*/ 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, buildUserDN(user)); ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password); 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 { closeConnections(ctx, tls); } }
From source file:org.kitodo.services.data.LdapServerService.java
/** * Check if connection with login and password possible. * * @param user/*from w ww . j a va2s . c o m*/ * User object * @param password * String * @return Login correct or not */ public boolean isUserPasswordCorrect(User user, String password) { logger.debug("start login session with ldap"); Hashtable<String, String> env = initializeWithLdapConnectionSettings(user.getLdapGroup().getLdapServer()); // Start TLS if (ConfigCore.getBooleanParameter(Parameters.LDAP_USE_TLS)) { logger.debug("use TLS for auth"); 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, buildUserDN(user)); ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password); 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.getMessage(), e); } } if (ctx != null) { try { // Close LDAP connection ctx.close(); } catch (NamingException e) { logger.error(e.getMessage(), 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, buildUserDN(user)); env.put(Context.SECURITY_CREDENTIALS, password); } logger.debug("ldap environment set"); try { logger.debug("start classic ldap authentication"); logger.debug("user DN is {}", buildUserDN(user)); if (ConfigCore.getParameter(Parameters.LDAP_ATTRIBUTE_TO_TEST) == 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(buildUserDN(user)); Attribute la = attrs.get(ConfigCore.getParameter(Parameters.LDAP_ATTRIBUTE_TO_TEST)); logger.debug("ldap attributes set"); String test = (String) la.get(0); if (test.equals(ConfigCore.getParameter(Parameters.LDAP_VALUE_OF_ATTRIBUTE))) { logger.debug("ldap ok"); ctx.close(); return true; } else { logger.debug("ldap not ok"); ctx.close(); return false; } } } catch (NamingException e) { logger.debug("login not allowed for {}. Exception: {}", user.getLogin(), e); return false; } } }
From source file:org.kitodo.services.data.LdapServerService.java
/** * Retrieve home directory of given user. * * @param user//from w w w . j a v a 2s. c o m * User object * @return path as URI */ public URI getUserHomeDirectory(User user) { URI userFolderBasePath = URI.create("file:///" + ConfigCore.getParameter(Parameters.DIR_USERS)); if (ConfigCore.getBooleanParameter(Parameters.LDAP_USE_LOCAL_DIRECTORY)) { return userFolderBasePath.resolve(user.getLogin()); } Hashtable<String, String> env = initializeWithLdapConnectionSettings(user.getLdapGroup().getLdapServer()); if (ConfigCore.getBooleanParameter(Parameters.LDAP_USE_TLS)) { 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(); ctx.reconnect(null); Attributes attrs = ctx.getAttributes(buildUserDN(user)); Attribute la = attrs.get("homeDirectory"); return URI.create((String) la.get(0)); // Perform search for privileged attributes under authenticated // context } catch (IOException e) { logger.error("TLS negotiation error:", e); return userFolderBasePath.resolve(user.getLogin()); } catch (NamingException e) { logger.error("JNDI error:", e); return userFolderBasePath.resolve(user.getLogin()); } finally { if (tls != null) { try { // Tear down TLS connection tls.close(); } catch (IOException e) { logger.error(e.getMessage(), e); } } if (ctx != null) { try { // Close LDAP connection ctx.close(); } catch (NamingException e) { logger.error(e.getMessage(), e); } } } } if (ConfigCore.getBooleanParameter("useSimpleAuthentification", false)) { env.put(Context.SECURITY_AUTHENTICATION, "none"); } DirContext ctx; URI userFolderPath = null; try { ctx = new InitialDirContext(env); Attributes attrs = ctx.getAttributes(buildUserDN(user)); Attribute ldapAttribute = attrs.get("homeDirectory"); userFolderPath = URI.create((String) ldapAttribute.get(0)); ctx.close(); } catch (NamingException e) { logger.error(e.getMessage(), e); } if (userFolderPath != null && !userFolderPath.isAbsolute()) { if (userFolderPath.getPath().startsWith("/")) { userFolderPath = serviceManager.getFileService().deleteFirstSlashFromPath(userFolderPath); } return userFolderBasePath.resolve(userFolderPath); } else { return userFolderPath; } }
From source file:org.lsc.jndi.JndiServices.java
private void initConnection() throws NamingException, IOException { // log new connection with it's details logConnectingTo(connProps);//from ww w . j a v a 2s .c om /* should we negotiate TLS? */ if (connProps.get(TLS_CONFIGURATION) != null && (Boolean) connProps.get(TLS_CONFIGURATION)) { /* if we're going to do TLS, we mustn't BIND before the STARTTLS operation * so we remove credentials from the properties to stop JNDI from binding */ /* duplicate properties to avoid changing them (they are used as a cache key in getInstance() */ Properties localConnProps = new Properties(); localConnProps.putAll(connProps); String jndiContextAuthentication = localConnProps.getProperty(Context.SECURITY_AUTHENTICATION); String jndiContextPrincipal = localConnProps.getProperty(Context.SECURITY_PRINCIPAL); String jndiContextCredentials = localConnProps.getProperty(Context.SECURITY_CREDENTIALS); localConnProps.remove(Context.SECURITY_AUTHENTICATION); localConnProps.remove(Context.SECURITY_PRINCIPAL); localConnProps.remove(Context.SECURITY_CREDENTIALS); /* open the connection */ ctx = new InitialLdapContext(localConnProps, null); /* initiate the STARTTLS extended operation */ try { tlsResponse = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest()); tlsResponse.negotiate(); } catch (IOException e) { LOGGER.error("Error starting TLS encryption on connection to {}", localConnProps.getProperty(Context.PROVIDER_URL)); LOGGER.debug(e.toString(), e); throw e; } catch (NamingException e) { LOGGER.error("Error starting TLS encryption on connection to {}", localConnProps.getProperty(Context.PROVIDER_URL)); LOGGER.debug(e.toString(), e); throw e; } /* now we add the credentials back to the context, to BIND once TLS is started */ ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, jndiContextAuthentication); ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, jndiContextPrincipal); ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, jndiContextCredentials); } else { /* don't start TLS, just connect normally (this can be on ldap:// or ldaps://) */ ctx = new InitialLdapContext(connProps, null); } /* get LDAP naming context */ try { namingContext = new LdapUrl((String) ctx.getEnvironment().get(Context.PROVIDER_URL)); } catch (LdapURLEncodingException e) { LOGGER.error(e.toString()); LOGGER.debug(e.toString(), e); throw new NamingException(e.getMessage()); } /* handle options */ contextDn = namingContext.getDn() != null ? namingContext.getDn() : null; String pageSizeStr = (String) ctx.getEnvironment().get("java.naming.ldap.pageSize"); if (pageSizeStr != null) { pageSize = Integer.parseInt(pageSizeStr); } else { pageSize = -1; } sortedBy = (String) ctx.getEnvironment().get("java.naming.ldap.sortedBy"); String recursiveDeleteStr = (String) ctx.getEnvironment().get("java.naming.recursivedelete"); if (recursiveDeleteStr != null) { recursiveDelete = Boolean.parseBoolean(recursiveDeleteStr); } else { recursiveDelete = false; } /* Load SyncRepl response control */ LdapApiService ldapApiService = LdapApiServiceFactory.getSingleton(); ControlFactory<?> factory = new SyncStateValueFactory(ldapApiService); ldapApiService.registerControl(factory); /* Load Persistent Search response control */ factory = new PersistentSearchFactory(ldapApiService); ldapApiService.registerControl(factory); }
From source file:org.lsc.jndi.JndiServices.java
/** * Return the LDAP schema./*from w w w . ja v a2 s .c om*/ * * @param attrsToReturn * list of attribute names to return (or null for all * 'standard' attributes) * @return the map of name => attribute * @throws NamingException * thrown if something goes wrong (bad */ @SuppressWarnings("unchecked") public Map<String, List<String>> getSchema(final String[] attrsToReturn) throws NamingException { Map<String, List<String>> attrsResult = new HashMap<String, List<String>>(); // connect to directory Hashtable<String, String> props = (Hashtable<String, String>) ctx.getEnvironment(); String baseUrl = (String) props.get(Context.PROVIDER_URL); baseUrl = baseUrl.substring(0, baseUrl.lastIndexOf('/')); props.put(Context.PROVIDER_URL, baseUrl); DirContext schemaCtx = new InitialLdapContext(props, null); // find schema entry SearchControls sc = new SearchControls(); sc.setSearchScope(SearchControls.OBJECT_SCOPE); sc.setReturningAttributes(new String[] { "subschemaSubentry" }); NamingEnumeration<SearchResult> schemaDnSR = schemaCtx.search("", "(objectclass=*)", sc); SearchResult sr = null; Attribute subschemaSubentry = null; String subschemaSubentryDN = null; if (schemaDnSR.hasMore()) { sr = schemaDnSR.next(); } if (sr != null) { subschemaSubentry = sr.getAttributes().get("subschemaSubentry"); } if (subschemaSubentry != null && subschemaSubentry.size() > 0) { subschemaSubentryDN = (String) subschemaSubentry.get(); } if (subschemaSubentryDN != null) { // get schema attributes from subschemaSubentryDN Attributes schemaAttrs = schemaCtx.getAttributes(subschemaSubentryDN, attrsToReturn != null ? attrsToReturn : new String[] { "*", "+" }); if (schemaAttrs != null) { for (String attr : attrsToReturn) { Attribute schemaAttr = schemaAttrs.get(attr); if (schemaAttr != null) { attrsResult.put(schemaAttr.getID(), (List<String>) Collections.list(schemaAttr.getAll())); } } } } return attrsResult; }
From source file:org.mule.module.ldap.api.jndi.LDAPJNDIConnection.java
/** * @param dn/*from ww w . j a v a2 s .c o m*/ * @param password * @throws LDAPException * @see org.mule.module.ldap.api.LDAPConnection#bind(java.lang.String, * java.lang.String) */ @Override public void bind(String dn, String password) throws LDAPException { try { if (!isClosed()) { String currentUrl = (String) getConn().getEnvironment().get(Context.PROVIDER_URL); String currentAuth = (String) getConn().getEnvironment().get(Context.SECURITY_AUTHENTICATION); String currentDn = getBindedUserDn(); logger.info("Already binded to " + currentUrl + " with " + currentAuth + " authentication as " + (currentDn != null ? currentDn : "anonymous") + ". Closing connection first."); close(); logger.info("Re-binding to " + getProviderUrl() + " with " + getAuthentication() + " authentication as " + (dn != null ? dn : "anonymous")); } logConfiguration(dn, password); setConn(new InitialLdapContext(buildEnvironment(dn, password), null)); logger.info("Binded to " + getProviderUrl() + " with " + getAuthentication() + " authentication as " + (dn != null ? dn : "anonymous")); } catch (NamingException nex) { throw handleNamingException(nex, "Bind failed."); } }
From source file:org.mule.providers.ldap.util.DSManager.java
/** * Sets the contexts of this class taking into account the extras and * overrides properties./*from w w w . j av a2 s . c om*/ * * @param env * an environment to use while setting up the system root. * @throws NamingException * if there is a failure of any kind */ protected void setContexts(Hashtable env) throws NamingException { Hashtable envFinal = new Hashtable(env); envFinal.put(Context.PROVIDER_URL, "ou=system"); sysRoot = new InitialLdapContext(envFinal, null); envFinal.put(Context.PROVIDER_URL, ""); rootDSE = new InitialLdapContext(envFinal, null); }
From source file:org.mule.transport.ldap.util.DSManager.java
protected void setContexts(final Hashtable<String, Object> env) throws Exception { final Hashtable<String, Object> envFinal = new Hashtable<String, Object>(env); // envFinal.put( Context.PROVIDER_URL, "dc=example,dc=com" ); // exampleRoot = new InitialLdapContext( envFinal, null ); // Hashtable<String, Object> envFinal = new Hashtable<String, Object>( // env );//from w ww.jav a2s .c om envFinal.put(Context.PROVIDER_URL, ServerDNConstants.SYSTEM_DN); sysRoot = new InitialLdapContext(envFinal, null); envFinal.put(Context.PROVIDER_URL, ""); rootDSE = directoryService.getAdminSession(); root = new InitialLdapContext(envFinal, null); envFinal.put(Context.PROVIDER_URL, ServerDNConstants.OU_SCHEMA_DN); schemaRoot = new InitialLdapContext(envFinal, null); }