List of usage examples for javax.naming Context SECURITY_AUTHENTICATION
String SECURITY_AUTHENTICATION
To view the source code for javax.naming Context SECURITY_AUTHENTICATION.
Click Source Link
From source file:fedora.server.security.servletfilters.ldap.FilterLdap.java
private Hashtable getEnvironment(String userid, String password) { String m = FilterSetup.getFilterNameAbbrev(FILTER_NAME) + " getEnvironment() "; Hashtable env = null;// ww w .j a v a2s . c o m try { env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); if (VERSION != null && !"".equals(VERSION)) { log.debug(m + "ldap explicit version==" + VERSION); env.put(CONTEXT_VERSION_KEY, VERSION); } log.debug(m + "ldap version==" + env.get(CONTEXT_VERSION_KEY)); env.put(Context.PROVIDER_URL, URL); log.debug(m + "ldap url==" + env.get(Context.PROVIDER_URL)); if (!bindRequired()) { log.debug(m + "\"binding\" anonymously"); } else { env.put(Context.SECURITY_AUTHENTICATION, SECURITY_AUTHENTICATION); String userForBind = null; String passwordForBind = null; if (!individualUserBind()) { userForBind = SECURITY_PRINCIPAL; passwordForBind = SECURITY_CREDENTIALS; log.debug(m + "binding to protected directory"); } else { passwordForBind = password; if (SECURITY_PRINCIPAL == null || "".equals(SECURITY_PRINCIPAL)) { userForBind = userid; log.debug(m + "binding for real user"); } else { //simulate test against user-bind at directory server userForBind = SECURITY_PRINCIPAL; log.debug(m + "binding for --test-- user"); } } env.put(Context.SECURITY_CREDENTIALS, passwordForBind); String[] parms = { userForBind }; String userFormattedForBind = applyFilter(BIND_FILTER, parms); env.put(Context.SECURITY_PRINCIPAL, userFormattedForBind); } log.debug(m + "bind w " + env.get(Context.SECURITY_AUTHENTICATION)); log.debug(m + "user== " + env.get(Context.SECURITY_PRINCIPAL)); log.debug(m + "passwd==" + env.get(Context.SECURITY_CREDENTIALS)); } catch (Throwable th) { if (LOG_STACK_TRACES) { log.error(m + "couldn't set up env for DirContext", th); } else { log.error(m + "couldn't set up env for DirContext" + th.getMessage()); } } finally { log.debug(m + "< " + env); } return env; }
From source file:com.nridge.core.app.ldap.ADQuery.java
/** * Returns <i>true</i> if the Active Directory account and password are * valid (e.g. a context can be successfully established) or <i>false</i> * otherwise.// w w w .j a v a 2 s . com * * @param anAccountName An Active Directory account name. * @param anAccountPassword An Active Directory account passowrd. * * @return <i>true</i> or <i>false</i> */ @SuppressWarnings("unchecked") public boolean isAccountValid(String anAccountName, String anAccountPassword) { boolean isValid = false; Logger appLogger = mAppMgr.getLogger(this, "isAccountValid"); appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER); DataBag userBag = schemaUserBag(); userBag.setValueByName(LDAP_ACCOUNT_NAME, anAccountName); try { loadUserByAccountName(userBag); Hashtable<String, String> environmentalVariables = new Hashtable<String, String>(); environmentalVariables.put("com.sun.jndi.ldap.connect.pool", StrUtl.STRING_TRUE); environmentalVariables.put(Context.PROVIDER_URL, getPropertyValue("domain_url", null)); environmentalVariables.put("java.naming.ldap.attributes.binary", "tokenGroups objectSid"); environmentalVariables.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); environmentalVariables.put(Context.SECURITY_PRINCIPAL, userBag.getValueAsString(LDAP_DISTINGUISHED_NAME)); environmentalVariables.put(Context.SECURITY_CREDENTIALS, anAccountPassword); environmentalVariables.put(Context.REFERRAL, getPropertyValue("referral_handling", "ignore")); environmentalVariables.put(Context.SECURITY_AUTHENTICATION, getPropertyValue("authentication", "simple")); LdapContext ldapContext = new InitialLdapContext(environmentalVariables, null); ldapContext.close(); isValid = true; } catch (Exception ignored) { } appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART); return isValid; }
From source file:com.openkm.principal.LdapPrincipalAdapter.java
/** * Create static LDAP configuration environment. *///from ww w. j a va 2s. c o m private static Hashtable<String, String> getEnvironment() { Hashtable<String, String> env = new Hashtable<String, String>(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.PROVIDER_URL, Config.PRINCIPAL_LDAP_SERVER); // Enable connection pooling // @see http://docs.oracle.com/javase/jndi/tutorial/ldap/connect/pool.html env.put("com.sun.jndi.ldap.connect.pool", "true"); /** * Referral values: ignore, follow or throw. * * @see http://docs.oracle.com/javase/jndi/tutorial/ldap/referral/jndi.html * @see http://java.sun.com/products/jndi/jndi-ldap-gl.html */ if (!"".equals(Config.PRINCIPAL_LDAP_REFERRAL)) { env.put(Context.REFERRAL, Config.PRINCIPAL_LDAP_REFERRAL); } // Optional is some cases (Max OS/X) if (!Config.PRINCIPAL_LDAP_SECURITY_PRINCIPAL.equals("")) { env.put(Context.SECURITY_PRINCIPAL, Config.PRINCIPAL_LDAP_SECURITY_PRINCIPAL); } if (!Config.PRINCIPAL_LDAP_SECURITY_CREDENTIALS.equals("")) { env.put(Context.SECURITY_CREDENTIALS, Config.PRINCIPAL_LDAP_SECURITY_CREDENTIALS); } return env; }
From source file:com.googlecode.fascinator.authentication.custom.ldap.CustomLdapAuthenticationHandler.java
private boolean bindSearchX(String username, String password, Hashtable<String, String> env, boolean bind) throws AuthenticationException, NamingException { env.put(Context.SECURITY_PRINCIPAL, ldapSecurityPrincipal); env.put(Context.SECURITY_CREDENTIALS, ldapSecurityCredentials); DirContext ctx = null;//from w w w . j av a2 s .c o m try { ctx = new InitialDirContext(env); } catch (NamingException ne) { log.error("Failed to bind as: {}", ldapSecurityPrincipal); } // ensure we have the userPassword attribute at a minimum String[] attributeList = new String[] { "userPassword" }; SearchControls sc = new SearchControls(); sc.setSearchScope(SearchControls.SUBTREE_SCOPE); sc.setReturningAttributes(attributeList); sc.setDerefLinkFlag(true); sc.setReturningObjFlag(false); sc.setTimeLimit(5000); String filter = "(" + filterPrefix + idAttr + "=" + username + filterSuffix + ")"; // Do the search NamingEnumeration<SearchResult> results = ctx.search(baseDn, filter, sc); if (!results.hasMore()) { log.warn("no valid user found."); return false; } SearchResult result = results.next(); log.debug("authenticating user: {}", result.getNameInNamespace()); if (bind) { // setup user context for binding Hashtable<String, String> userEnv = new Hashtable<String, String>(); userEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); userEnv.put(Context.SECURITY_AUTHENTICATION, "simple"); userEnv.put(Context.PROVIDER_URL, baseUrl); userEnv.put(Context.SECURITY_PRINCIPAL, result.getNameInNamespace()); userEnv.put(Context.SECURITY_CREDENTIALS, password); try { new InitialDirContext(userEnv); } catch (NamingException ne) { log.error("failed to authenticate user: " + result.getNameInNamespace()); throw ne; } } else { // get userPassword attribute Attribute up = result.getAttributes().get("userPassword"); if (up == null) { log.error("unable to read userPassword attribute for: {}", result.getNameInNamespace()); return false; } byte[] userPasswordBytes = (byte[]) up.get(); String userPassword = new String(userPasswordBytes); // compare passwords - also handles encodings if (!passwordsMatch(password, userPassword)) { return false; } } return true; }
From source file:com.alfaariss.oa.util.idmapper.jndi.JNDIMapper.java
/** * Reads JNDI connection information from the configuration. * <br>/*from w ww .java 2s.c o m*/ * Creates an <code>Hashtable</code> containing the JNDI environment variables. * @param oConfigurationManager The configuration manager * @param eConfig the configuration section * @return <code>DirContext</code> that contains the JNDI connection * @throws OAException if configuration reading fails */ private Hashtable<String, String> readJNDIContext(IConfigurationManager oConfigurationManager, Element eConfig) throws OAException { Hashtable<String, String> htEnvironment = new Hashtable<String, String>(11); try { Element eSecurityPrincipal = oConfigurationManager.getSection(eConfig, "security_principal"); if (eSecurityPrincipal == null) { _logger.error("No 'security_principal' section found in 'resource' configuration"); throw new OAException(SystemErrors.ERROR_CONFIG_READ); } String sPrincipal = oConfigurationManager.getParam(eSecurityPrincipal, "dn"); if (sPrincipal == null) { _logger.error("No item 'dn' item found in configuration"); throw new OAException(SystemErrors.ERROR_CONFIG_READ); } String sPassword = oConfigurationManager.getParam(eSecurityPrincipal, "password"); if (sPassword == null) { _logger.error("No 'password' item found in configuration "); throw new OAException(SystemErrors.ERROR_CONFIG_READ); } String sDriver = oConfigurationManager.getParam(eConfig, "driver"); if (sDriver == null) { _logger.error("No 'driver' item found in configuration"); throw new OAException(SystemErrors.ERROR_CONFIG_READ); } String sUrl = oConfigurationManager.getParam(eConfig, "url"); if (sUrl == null) { _logger.error("No valid config item 'url' found in configuration"); throw new OAException(SystemErrors.ERROR_CONFIG_READ); } if (sUrl.length() >= 5 && sUrl.substring(0, 5).equalsIgnoreCase("ldaps")) { // Request SSL transport htEnvironment.put(Context.SECURITY_PROTOCOL, "ssl"); _logger.info("SSL enabled"); } else { _logger.info("SSL disabled"); } htEnvironment.put(Context.INITIAL_CONTEXT_FACTORY, sDriver); htEnvironment.put(Context.SECURITY_AUTHENTICATION, "simple"); htEnvironment.put(Context.SECURITY_PRINCIPAL, sPrincipal); htEnvironment.put(Context.SECURITY_CREDENTIALS, sPassword); htEnvironment.put(Context.PROVIDER_URL, sUrl); } catch (OAException e) { throw e; } catch (Exception e) { _logger.error("Could not create a connection", e); throw new OAException(SystemErrors.ERROR_INTERNAL); } return htEnvironment; }
From source file:io.apiman.gateway.engine.policies.BasicAuthLDAPTest.java
private DirContext createContext() throws NamingException { // Create a environment container Hashtable<Object, Object> env = new Hashtable<>(); String url = "ldap://" + LDAP_SERVER + ":" + ldapServer.getPort(); // Create a new context pointing to the partition env.put(Context.PROVIDER_URL, url); env.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system"); env.put(Context.SECURITY_CREDENTIALS, "secret"); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); // Let's open a connection on this partition InitialContext initialContext = new InitialContext(env); // We should be able to read it DirContext appRoot = (DirContext) initialContext.lookup(""); Assert.assertNotNull(appRoot);/* w w w .j a va 2s. c o m*/ return appRoot; }
From source file:com.communote.server.test.ldap.AbstractApacheDSServer.java
/** * Sets the contexts for this base class. Values of user and password used to set the respective * JNDI properties. These values can be overriden by the overrides properties. * * @param user//from w w w .j av a 2s . c om * the username for authenticating as this user * @param passwd * the password of the user * @throws Exception * if there is a failure of any kind */ protected void setContexts(String user, String passwd) throws Exception { Hashtable<String, Object> env = new Hashtable<String, Object>(); env.put(DirectoryService.JNDI_KEY, getDirectoryService()); env.put(Context.SECURITY_PRINCIPAL, user); env.put(Context.SECURITY_CREDENTIALS, passwd); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.INITIAL_CONTEXT_FACTORY, CoreContextFactory.class.getName()); setContexts(env); }
From source file:com.headstrong.fusion.messaging.model.endpoint.binding.JmsBindingEndPointModeler.java
/** * Creates a {@link JmsComponent} using the parameters set. * /* w w w.j ava 2 s. co m*/ * @param routeBuilder * @return {@link JmsComponent} * @throws ProcessModellingException */ @SuppressWarnings("unchecked") private Component getJmsComponent(RouteBuilder routeBuilder) throws ProcessModellingException { JmsComponent jmsComponent = null; if (this.getProvider().equals(Provider.activemq.toString())) { jmsComponent = ActiveMQComponent.activeMQComponent(); jmsComponent.setConnectionFactory(new PooledConnectionFactory(this.getBrokerUrl())); jmsComponent.setCamelContext(routeBuilder.getContext()); jmsComponent.setAcknowledgementMode(Session.AUTO_ACKNOWLEDGE); } else if (this.getProvider().equals(Provider.ibmmq.toString())) { JmsConnectionFactory factory = null; try { JmsFactoryFactory jmsFactoryFactory; jmsFactoryFactory = JmsFactoryFactory.getInstance(JmsConstants.WMQ_PROVIDER); factory = jmsFactoryFactory.createConnectionFactory(); factory.setIntProperty(WMQConstants.WMQ_CONNECTION_MODE, WMQConstants.WMQ_CM_CLIENT); factory.setStringProperty(WMQConstants.WMQ_QUEUE_MANAGER, this.getQueueManager()); factory.setStringProperty(WMQConstants.WMQ_HOST_NAME, this.getBrokerUrl()); factory.setIntProperty(WMQConstants.WMQ_PORT, this.getPort()); if (this.getChannel() != null && !this.getChannel().isEmpty()) factory.setStringProperty(WMQConstants.WMQ_CHANNEL, this.getChannel()); factory.setIntProperty(WMQConstants.DELIVERY_MODE, this.getDeliveryMode()); } catch (JMSException e) { logger.error("Error connecting to JMS provider.", e); throw new ProcessModellingException("Error connecting to JMS provider.", e); } UserCredentialsConnectionFactoryAdapter adapter = new UserCredentialsConnectionFactoryAdapter(); adapter.setTargetConnectionFactory(factory); if (this.getUserName() != null) { adapter.setUsername(this.getUserName()); } if (this.getPassword() != null) { adapter.setPassword(this.getPassword()); } jmsComponent = JmsComponent.jmsComponent(); jmsComponent.setConnectionFactory(adapter); jmsComponent.setCamelContext(routeBuilder.getContext()); jmsComponent.setAcknowledgementMode(Session.AUTO_ACKNOWLEDGE); } else { Hashtable<String, String> prop = new Hashtable<String, String>(); // Mandatory property. prop.put(Context.PROVIDER_URL, this.getLdapConfiguration().getProviderUrl()); prop.put(Context.INITIAL_CONTEXT_FACTORY, this.getLdapConfiguration().getInitialContextFactory()); // Only these optional properties supported now. if (this.getLdapConfiguration().getSecurityAuthentication() != null) { prop.put(Context.SECURITY_AUTHENTICATION, this.getLdapConfiguration().getSecurityAuthentication()); } if (this.getLdapConfiguration().getSecutiryPrincipal() != null) { prop.put(Context.SECURITY_PRINCIPAL, this.getLdapConfiguration().getSecutiryPrincipal()); } if (this.getLdapConfiguration().getSecutiryCredentials() != null) { prop.put(Context.SECURITY_CREDENTIALS, this.getLdapConfiguration().getSecutiryCredentials()); } Context context; ConnectionFactory connectionFactory; try { // HACK required to avoid ClassNotFoundException while // retrieving the // InitialContext. ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); context = new InitialContext(prop); connectionFactory = (ConnectionFactory) context .lookup(this.getLdapConfiguration().getConnectionFactoryJndiName()); } finally { Thread.currentThread().setContextClassLoader(contextClassLoader); } // HACK -- Finished } catch (NamingException e) { logger.error("Error connecting to JMS provider.", e); throw new ProcessModellingException("Error connecting to JMS provider.", e); } UserCredentialsConnectionFactoryAdapter adapter = new UserCredentialsConnectionFactoryAdapter(); adapter.setTargetConnectionFactory(connectionFactory); if (this.getUserName() != null) { adapter.setUsername(this.getUserName()); } if (this.getPassword() != null) { adapter.setPassword(this.getPassword()); } jmsComponent = JmsComponent.jmsComponent(); jmsComponent.setConnectionFactory(adapter); jmsComponent.setCamelContext(routeBuilder.getContext()); jmsComponent.setAcknowledgementMode(Session.AUTO_ACKNOWLEDGE); } if (jmsComponent != null) { jmsComponent.setConcurrentConsumers(getThreadCount()); } return jmsComponent; }
From source file:ldap.ActiveLoginImpl.java
/** * open the directory connection./*from w w w. j a va 2 s . com*/ * @param url * @param tracing * @return * @throws NamingException */ private DirContext setupJNDIConnection(String url, String userDN, String password, boolean tracing) throws NamingException { /* * First, set up a large number of environment variables to sensible default valuse */ Hashtable env = new Hashtable(); // sanity check if (url == null) throw new NamingException("URL not specified in openContext()!"); // set the tracing level now, since it can't be set once the connection is open. if (tracing) env.put("com.sun.jndi.ldap.trace.ber", System.err); // echo trace to standard error output //env.put("java.naming.ldap.version", "3"); // always use ldap v3 - v2 too limited env.put(LdapConstants.ldapVersionStr, LdapConstants.ldapVersion); // always use ldap v3 - v2 too limited //env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); // use default jndi provider env.put(Context.INITIAL_CONTEXT_FACTORY, LdapConstants.ldapContext); // use default jndi provider //env.put("java.naming.ldap.deleteRDN", "false"); // usually what we want env.put(LdapConstants.ldapDeleteRdn, LdapConstants.ldapDeleteRdnValue); // usually what we want //env.put(Context.REFERRAL, "ignore"); //could be: follow, ignore, throw env.put(Context.REFERRAL, LdapConstants.ldapIgnore); //could be: follow, ignore, throw // env.put("java.naming.ldap.derefAliases", "finding"); // could be: finding, searching, etc. env.put(LdapConstants.ldapFindingAliases, LdapConstants.ldapFindingStr); // could be: finding, searching, etc. //env.put(Context.SECURITY_AUTHENTICATION, "simple"); // 'simple' = username + password env.put(Context.SECURITY_AUTHENTICATION, LdapConstants.ldapSecurityAuth); // 'simple' = username + password env.put(Context.SECURITY_PRINCIPAL, userDN); // add the full user dn env.put(Context.SECURITY_CREDENTIALS, password); // stupid jndi requires us to cast this to a string- env.put(Context.PROVIDER_URL, url); // the ldap url to connect to; e.g. "ldap://ca.com:389" /* * Open the actual LDAP session using the above environment variables */ DirContext newContext = new InitialDirContext(env); if (newContext == null) throw new NamingException( "Internal Error with jndi connection: No Context was returned, however no exception was reported by jndi."); return newContext; }
From source file:com.stimulus.archiva.security.realm.ADRealm.java
public ArrayList<AttributeValue> getADAttributes(Config config, ADIdentity identity, String username, String password) throws ArchivaException { logger.debug("getADAttributes()"); validateLoginName(username);/*from w w w . j a va2 s . c o m*/ validatePassword(password); LoginContext serverLC = kereberosLogin(config, identity, identity.getServiceDN(), identity.getServicePassword()); Hashtable<String, String> env = new Hashtable<String, String>(11); String ldapAddress = identity.getLDAPAddress(); if (!ldapAddress.toLowerCase(Locale.ENGLISH).startsWith("ldap://")) ldapAddress = "ldap://" + ldapAddress; logger.debug("finding DN of user from LDAP using Kereberos token {ldapAddress='" + ldapAddress + "', username='" + username + "'}"); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, ldapAddress); env.put(Context.SECURITY_AUTHENTICATION, "GSSAPI"); int at = username.indexOf('@'); String uname = username; if (uname.indexOf("@") != -1) { uname = username.substring(0, at).toLowerCase(Locale.ENGLISH); } logger.debug("findUserDN {loginname='" + uname + "'}"); String bindDN = null; try { bindDN = (String) Subject.doAs(serverLC.getSubject(), new FindDNAction(identity, uname, env)); } catch (Exception e) { throw new ArchivaException("failed to bind to ldap server {uname='" + username + "''}", e, logger); } try { serverLC.logout(); } catch (Exception e) { throw new ArchivaException("failed to logout from kerberos server:" + e.getMessage() + " {uname='" + username + "',kdcAddress='" + identity.getKDCAddress() + "'}", e, logger); } ArrayList<AttributeValue> attributes = new ArrayList<AttributeValue>(); serverLC = kereberosLogin(config, identity, username, password); if (bindDN != null) { env.clear(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, ldapAddress); env.put(Context.SECURITY_AUTHENTICATION, "GSSAPI"); try { attributes = (ArrayList<AttributeValue>) Subject.doAs(serverLC.getSubject(), new GetAttributesAction(identity, username, env, bindDN)); } catch (Exception e) { throw new ArchivaException("failed to bind to ldap server:" + e.getMessage() + " {uname='" + username + "',ldapAddress='" + identity.getLDAPAddress() + "'}", e, logger); } } try { serverLC.logout(); } catch (Exception e) { throw new ArchivaException("failed to logout from kerberos server:" + e.getMessage() + " {uname='" + username + "',kdcAddress='" + identity.getKDCAddress() + "'}", e, logger); } logger.debug("getADAttributes() return"); return attributes; }