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: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); }//from w ww .j a v a2 s . 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:com.communote.server.test.ldap.AbstractApacheDSServer.java
/** * Common code to get an initial context via a simple bind to the server over the wire using the * SUN JNDI LDAP provider. Do not use this method until after the setUp() method is called to * start the server otherwise it will fail. * * @param bindPrincipalDn/*from www .j a va 2 s. c o m*/ * the DN of the principal to bind as * @param password * the password of the bind principal * @return an LDAP context as the the administrator to the rootDSE * @throws Exception * if the server cannot be contacted */ protected LdapContext getWiredContext(String bindPrincipalDn, String password) throws Exception { // if ( ! apacheDS.isStarted() ) // { // throw new ConfigurationException( "The server is not online! Cannot connect to it." ); // } Hashtable<String, String> env = new Hashtable<String, String>(); env.put(Context.INITIAL_CONTEXT_FACTORY, CTX_FACTORY); env.put(Context.PROVIDER_URL, "ldap://localhost:" + getPort()); env.put(Context.SECURITY_PRINCIPAL, bindPrincipalDn); env.put(Context.SECURITY_CREDENTIALS, password); env.put(Context.SECURITY_AUTHENTICATION, "simple"); return new InitialLdapContext(env, null); }
From source file:com.alfaariss.oa.authentication.password.jndi.JNDIProtocolResource.java
private boolean doBind(String sUserID, String sPassword) throws OAException, UserException { StringBuffer sbTemp = null;/*from w w w . ja v a 2 s . c o m*/ DirContext oDirContext = null; String sQuery = null; String sRelUserDn = null; boolean bResult = false; NamingEnumeration enumSearchResults = null; Hashtable<String, String> htEnvironment = new Hashtable<String, String>(); htEnvironment.put(Context.PROVIDER_URL, _sJNDIUrl); htEnvironment.put(Context.INITIAL_CONTEXT_FACTORY, _sDriver); htEnvironment.put(Context.SECURITY_AUTHENTICATION, "simple"); if (_bSSL) { htEnvironment.put(Context.SECURITY_PROTOCOL, "ssl"); } if (_sPrincipalDn.length() <= 0) // If no principal dn is known, we do a simple binding { String sEscUserID = JNDIUtil.escapeDN(sUserID); _logger.debug("Escaped user: " + sEscUserID); sbTemp = new StringBuffer(_sUserDn); sbTemp.append('='); sbTemp.append(sEscUserID); sbTemp.append(", "); sbTemp.append(_sBaseDn); htEnvironment.put(Context.SECURITY_PRINCIPAL, sbTemp.toString()); htEnvironment.put(Context.SECURITY_CREDENTIALS, sPassword); try { oDirContext = new InitialDirContext(htEnvironment); bResult = true; } catch (AuthenticationException e) { // If supplied credentials are invalid or when authentication fails // while accessing the directory or naming service. _logger.debug("Could not authenticate user (invalid password): " + sUserID, e); } catch (CommunicationException eC) { // If communication with the directory or naming service fails. _logger.warn("A communication error has occured", eC); throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE); } catch (NamingException eN) { // The initial dir context could not be created. _logger.warn("A naming error has occured", eN); throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE); } finally { try { if (oDirContext != null) { oDirContext.close(); } } catch (Exception e) { _logger.warn("Could not close connection with '" + _sJNDIUrl + '\'', e); } } } else //search through the subtree { // 1 - Try to bind to LDAP using the security principal's DN and its password htEnvironment.put(Context.SECURITY_PRINCIPAL, _sPrincipalDn); htEnvironment.put(Context.SECURITY_CREDENTIALS, _sPrincipalPwd); try { oDirContext = new InitialDirContext(htEnvironment); } catch (AuthenticationException eA) { _logger.warn("Could not bind to LDAP server", eA); throw new OAException(SystemErrors.ERROR_RESOURCE_CONNECT); } catch (CommunicationException eC) { _logger.warn("A communication error has occured", eC); throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE); } catch (NamingException eN) { _logger.warn("A naming error has occured", eN); throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE); } // 2 - Search through the context for user's DN relative to the base DN sQuery = resolveSearchQuery(sUserID); SearchControls oScope = new SearchControls(); oScope.setSearchScope(SearchControls.SUBTREE_SCOPE); try { enumSearchResults = oDirContext.search(_sBaseDn, sQuery, oScope); } catch (NamingException eN) { _logger.warn("User id not found in password backend for user: " + sUserID, eN); throw new UserException(UserEvent.AUTHN_METHOD_NOT_SUPPORTED); } finally { try { oDirContext.close(); oDirContext = null; } catch (Exception e) { _logger.warn("Could not close connection with '" + _sJNDIUrl + "'", e); } } try { if (!enumSearchResults.hasMoreElements()) { StringBuffer sb = new StringBuffer("User '"); sb.append(sUserID); sb.append("' not found during LDAP search. The filter was: '"); sb.append(sQuery); sb.append("'"); _logger.warn(sb.toString()); throw new UserException(UserEvent.AUTHN_METHOD_NOT_SUPPORTED); } SearchResult searchResult = (SearchResult) enumSearchResults.next(); sRelUserDn = searchResult.getName(); if (sRelUserDn == null) { _logger.warn("no user dn was returned for '" + sUserID + "'."); throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE); } } catch (NamingException eN) { _logger.warn("failed to fetch profile of user '" + sUserID + "'.", eN); throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE); } // 3 - Bind user using supplied credentials sbTemp = new StringBuffer(sRelUserDn); sbTemp.append(","); sbTemp.append(_sBaseDn); htEnvironment.put(Context.SECURITY_PRINCIPAL, sbTemp.toString()); htEnvironment.put(Context.SECURITY_CREDENTIALS, sPassword); try { oDirContext = new InitialDirContext(htEnvironment); bResult = true; } catch (AuthenticationException e) { _logger.debug("Could not authenticate user (invalid password): " + sUserID, e); } catch (CommunicationException eC) { _logger.warn("A communication error has occured", eC); throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE); } catch (NamingException eN) { _logger.warn("A naming error has occured", eN); throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE); } finally { try { if (oDirContext != null) { oDirContext.close(); } } catch (Exception e) { _logger.warn("Could not close connection with '" + _sJNDIUrl + "'.", e); } } } return bResult; }
From source file:com.nridge.core.app.ldap.ADQuery.java
/** * Opens a connection to Active Directory by establishing an initial LDAP * context. The security principal and credentials are assigned the * account name and password parameters. * * @param anAcountDN Active Directory account name (DN format). * @param anAccountPassword Active Directory account password. * * @throws NSException Thrown if an LDAP naming exception is occurs. *///from w w w . j a v a 2 s. c o m @SuppressWarnings("unchecked") public void open(String anAcountDN, String anAccountPassword) throws NSException { Logger appLogger = mAppMgr.getLogger(this, "open"); appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER); // LDAP Reference - http://docs.oracle.com/javase/1.5.0/docs/guide/jndi/jndi-ldap-gl.html 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, anAcountDN); environmentalVariables.put(Context.SECURITY_CREDENTIALS, anAccountPassword); // Referral options: follow, throw, ignore (default) environmentalVariables.put(Context.REFERRAL, getPropertyValue("referral_handling", "ignore")); // Authentication options: simple, DIGEST-MD5 CRAM-MD5 environmentalVariables.put(Context.SECURITY_AUTHENTICATION, getPropertyValue("authentication", "simple")); try { mLdapContext = new InitialLdapContext(environmentalVariables, null); } catch (NamingException e) { String msgStr = String.format("LDAP Context Error: %s", e.getMessage()); appLogger.error(msgStr, e); throw new NSException(msgStr); } appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART); }
From source file:edu.internet2.middleware.subject.provider.JNDISourceAdapter.java
/** * Setup environment./*from w ww .j ava 2s . c om*/ * @param props * @throws SourceUnavailableException */ protected void setupEnvironment(Properties props) throws SourceUnavailableException { this.environment.put("com.sun.jndi.ldap.connect.pool", "true"); this.environment.put(Context.INITIAL_CONTEXT_FACTORY, props.getProperty("INITIAL_CONTEXT_FACTORY")); this.environment.put(Context.PROVIDER_URL, props.getProperty("PROVIDER_URL")); this.environment.put(Context.SECURITY_AUTHENTICATION, props.getProperty("SECURITY_AUTHENTICATION")); this.environment.put(Context.SECURITY_PRINCIPAL, props.getProperty("SECURITY_PRINCIPAL")); String password = props.getProperty("SECURITY_CREDENTIALS"); password = Morph.decryptIfFile(password); this.environment.put(Context.SECURITY_CREDENTIALS, password); if (props.getProperty("SECURITY_PROTOCOL") != null) { this.environment.put(Context.SECURITY_PROTOCOL, "ssl"); } Context context = null; try { log.debug("Creating Directory Context"); context = new InitialDirContext(this.environment); } catch (AuthenticationException ex) { log.error("Error with Authentication " + ex.getMessage(), ex); throw new SourceUnavailableException("Error with Authentication ", ex); } catch (NamingException ex) { log.error("Naming Error " + ex.getMessage(), ex); throw new SourceUnavailableException("Naming Error", ex); } finally { if (context != null) { try { context.close(); } catch (NamingException ne) { // squelch, since it is already closed } } } log.info("Success in connecting to LDAP"); this.nameAttributeName = props.getProperty("Name_AttributeType"); if (this.nameAttributeName == null) { log.error("Name_AttributeType not defined"); } this.subjectIDAttributeName = props.getProperty("SubjectID_AttributeType"); if (this.subjectIDAttributeName == null) { log.error("SubjectID_AttributeType not defined"); } this.descriptionAttributeName = props.getProperty("Description_AttributeType"); if (this.descriptionAttributeName == null) { log.error("Description_AttributeType not defined"); } }
From source file:ldap.LdapApi.java
/** * open the directory connection./*from w w w . j a va2 s. c om*/ * @param url * @param dn * @param password * @param tracing * @return DirContext - context * @throws NamingException */ private DirContext setupJNDIConnection(String url, String userDN, String password, boolean tracing) throws NamingException { /* * setup environment variables to sensible default valuse */ Hashtable env = new Hashtable(); // sanity check if (url == null) { throw new LdapException("URL not specified in openContext()!"); } // tracing on/off, 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, LdapConstants.ldapContext); // use default jndi provider 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 */ context = new InitialDirContext(env); if (context == null) { throw new NamingException( "Internal Error with jndi connection: No Context was returned, however no exception was reported by jndi."); } else { logger.info("context is not null"); } return context; }
From source file:com.springsource.insight.plugin.ldap.LdapOperationCollectionAspectTestSupport.java
protected static final Hashtable<String, Object> createEnvironment() { Hashtable<String, Object> env = new Hashtable<String, Object>(); env.put(Context.PROVIDER_URL, LDAP_URL); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.SECURITY_PRINCIPAL, LDAP_USERNAME); env.put(Context.SECURITY_CREDENTIALS, LDAP_PASSWORD); return env;/*from w w w. ja v a 2 s. c o m*/ }
From source file:de.sub.goobi.helper.ldap.Ldap.java
/** * retrieve home directory of given user. * * @param inBenutzer/*from w ww . ja v a 2s. 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:com.aurel.track.util.LdapUtil.java
/** * Gets the initial context/* w w w . j a va 2 s . c o m*/ * * @param providerUrl * @param bindDN * @param bindPassword * @return */ public static LdapContext getInitialContext(String providerUrl, String bindDN, String bindPassword) { List<String> trace = new ArrayList<String>(); LOGGER.debug("providerURL: " + providerUrl); trace.add("Attempting to connect to the LDAP server..."); if (providerUrl != null && providerUrl.startsWith("ldaps:")) { System.setProperty("javax.net.ssl.trustStore", PATH_TO_KEY_STORE); trace.add("Using ldaps: with keystore at " + PATH_TO_KEY_STORE); File ks = new File(PATH_TO_KEY_STORE); if (!ks.exists()) { trace.add("*** There is no keystore at " + PATH_TO_KEY_STORE); } } if (providerUrl == null) { LOGGER.warn("LDAP provider URL should not be null."); return null; } Hashtable<String, Object> env = new Hashtable<String, Object>(); if (LOGGER.isDebugEnabled()) { env.put("com.sun.jndi.ldape.trace.ber", System.err); } env.put("java.naming.ldap.version", "3"); env.put("com.sun.jndi.ldap.connect.timeout", "10000"); env.put("com.sun.jndi.dns.timeout.initial", "2000"); env.put("com.sun.jndi.dns.timeout.retries", "3"); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, providerUrl); if ((bindDN != null) && !bindDN.equals("")) { env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, bindDN); env.put(Context.SECURITY_CREDENTIALS, bindPassword); LOGGER.debug("bind with bindDN:" + bindDN + " " + "bindPassword=" + bindPassword.replaceAll(".", "*")); trace.add("Preparing to bind to the LDAP server with DN = " + bindDN + " and password '****"); } else { LOGGER.debug("bind anonymous"); trace.add("Preparing to bind anonymously to the LDAP server"); } try { return new InitialLdapContext(env, null); } catch (NamingException e) { for (String msg : trace) { LOGGER.error(msg); } LOGGER.error("Getting the initial ldap context failed with " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); try { new InitialDirContext(env); } catch (NamingException e1) { LOGGER.error("Getting the initial dir context failed with " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); } return null; } }