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:ru.efo.security.ADUserDetailsService.java
private DirContext getDirContext(String username, String password) throws NamingException { final Properties props = new Properties(); props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); props.put(Context.SECURITY_AUTHENTICATION, "simple"); props.put(Context.SECURITY_PRINCIPAL, username); props.put(Context.SECURITY_CREDENTIALS, password); props.put(Context.PROVIDER_URL, ldapUrl); props.put("java.naming.ldap.attributes.binary", "objectSID"); return new InitialDirContext(props); }
From source file:jp.ikedam.jenkins.plugins.ldap_sasl.LdapSaslSecurityRealm.java
/** * Authorize a user./* w w w . j a v a 2 s . c om*/ * * @param username * @param password * @see hudson.security.AbstractPasswordBasedSecurityRealm#authenticate(java.lang.String, java.lang.String) */ @Override protected UserDetails authenticate(String username, String password) throws AuthenticationException { Logger logger = getLogger(); // check configuration. String ldapUris = getValidLdapUris(); if (StringUtils.isBlank(ldapUris)) { logger.severe("No valid LDAP URI is specified."); throw new AuthenticationServiceException("No valid LDAP URI is specified."); } String mechanisms = getMechanisms(); if (StringUtils.isBlank(mechanisms)) { logger.severe("No valid mechanism is specified."); throw new AuthenticationServiceException("No valid mechanism is specified."); } // TODO: Test with LDAPS. // Parameters for JNDI Hashtable<String, Object> env = new Hashtable<String, Object>(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, ldapUris); env.put(Context.SECURITY_PRINCIPAL, username); env.put(Context.SECURITY_CREDENTIALS, password); env.put(Context.SECURITY_AUTHENTICATION, mechanisms); env.put("com.sun.jndi.ldap.connect.timeout", Integer.toString(getConnectionTimeout())); env.put("com.sun.jndi.ldap.read.timeout", Integer.toString(getReadTimeout())); logger.fine("Authenticating with LDAP-SASL:"); logger.fine(String.format("username=%s", username)); logger.fine(String.format("servers=%s", ldapUris)); logger.fine(String.format("mech=%s", mechanisms)); LdapContext ctx = null; try { ctx = new InitialLdapContext(env, null); } catch (javax.naming.AuthenticationException e) { // Authentication Failure... throw new BadCredentialsException(String.format("Authentication failed: %s", username), e); } catch (NamingException e) { // Unexpected failure... throw new AuthenticationServiceException(String.format("Authentication failed: %s", username), e); } String userDn = (getUserDnResolver() != null) ? getUserDnResolver().getUserDn(ctx, username) : null; logger.fine(String.format("User DN is %s", userDn)); List<GrantedAuthority> authorities = (getGroupResolver() != null) ? getGroupResolver().resolveGroup(ctx, userDn, username) : new ArrayList<GrantedAuthority>(); logger.fine("Authenticating succeeded."); return new LdapUser(username, "", // password(not used) userDn, // dn of this user. true, // enabled true, // accountNonExpired true, // credentialsNonExpired true, // accountNonLocked authorities.toArray(new GrantedAuthority[0])); }
From source file:com.alfaariss.oa.engine.attribute.gather.processor.jndi.JNDIGatherer.java
/** * Reads JNDI connection information from the configuration. * <br>/* w w w. jav a2 s .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 AttributeException if configuration reading fails */ private Hashtable<String, String> readJNDIContext(IConfigurationManager oConfigurationManager, Element eConfig) throws AttributeException { 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 AttributeException(SystemErrors.ERROR_CONFIG_READ); } String sPrincipal = oConfigurationManager.getParam(eSecurityPrincipal, "dn"); if (sPrincipal == null) { _logger.error("No item 'dn' item found in configuration"); throw new AttributeException(SystemErrors.ERROR_CONFIG_READ); } String sPassword = oConfigurationManager.getParam(eSecurityPrincipal, "password"); if (sPassword == null) { _logger.error("No 'password' item found in configuration "); throw new AttributeException(SystemErrors.ERROR_CONFIG_READ); } String sDriver = oConfigurationManager.getParam(eConfig, "driver"); if (sDriver == null) { _logger.error("No 'driver' item found in configuration"); throw new AttributeException(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 AttributeException(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 (AttributeException e) { throw e; } catch (Exception e) { _logger.error("Could not create a connection", e); throw new AttributeException(SystemErrors.ERROR_INTERNAL); } return htEnvironment; }
From source file:com.alfaariss.oa.engine.user.provisioning.storage.external.jndi.JNDIExternalStorage.java
/** * Reads JNDI connection information from the configuration. * <br>/* w ww . jav a 2 s. 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 UserException if configuration reading fails */ private Hashtable<String, String> readJNDIContext(IConfigurationManager oConfigurationManager, Element eConfig) throws UserException { Hashtable<String, String> htEnvironment = new Hashtable<String, String>(); try { Element eSecurityPrincipal = oConfigurationManager.getSection(eConfig, "security_principal"); if (eSecurityPrincipal == null) { _logger.error("No 'security_principal' section found in 'resource' configuration"); throw new UserException(SystemErrors.ERROR_CONFIG_READ); } String sPrincipal = oConfigurationManager.getParam(eSecurityPrincipal, "dn"); if (sPrincipal == null) { _logger.error("No item 'dn' item found in configuration"); throw new UserException(SystemErrors.ERROR_CONFIG_READ); } String sPassword = oConfigurationManager.getParam(eSecurityPrincipal, "password"); if (sPassword == null) { _logger.error("No 'password' item found in configuration "); throw new UserException(SystemErrors.ERROR_CONFIG_READ); } String sDriver = oConfigurationManager.getParam(eConfig, "driver"); if (sDriver == null) { _logger.error("No 'driver' item found in configuration"); throw new UserException(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 UserException(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 (UserException e) { throw e; } catch (Exception e) { _logger.error("Could not create a connection", e); throw new UserException(SystemErrors.ERROR_INTERNAL, e); } return htEnvironment; }
From source file:com.adito.activedirectory.ActiveDirectoryUserDatabase.java
private void assertSimpleCredentialsValid(final String username, final String password) throws Throwable { RetryPrivilegedAction action = new RetryPrivilegedAction() { protected Object doIt(InitialLdapContext context) { return null; }//from w ww . j a v a 2 s . c om protected InitialLdapContext getContext(String url) throws Exception { String userDn = ((ActiveDirectoryUser) getAccount(username)).getOriginalDn(); Map<String, String> variables = new HashMap<String, String>(3); variables.put(Context.SECURITY_AUTHENTICATION, configuration.getUserAuthenticationType()); variables.put(Context.SECURITY_PRINCIPAL, userDn); variables.put(Context.SECURITY_CREDENTIALS, password); return configuration.getInitialContext(url, variables); } }; Object result = action.run(); if (result instanceof Throwable) { throw (Throwable) result; } }
From source file:com.funambol.LDAP.security.LDAPUserProvisioningOfficer.java
/** * return false if user or password is wrong * /*from w w w . j a v a 2 s. c o m*/ * here we expand attributes: %u, %d, %s * if defined userSearch, retrieve user's DN and try to bind with it * @param username * @param password * @return */ private boolean ldapBind(String username, String password) { String userDN = null; try { TempParams t = new TempParams(); // if username is an email substitute %u e %d in baseDn: expandSearchAndBaseDn(username, t); // setup the default LdapInterface configured with bean data ldapInterface = LDAPManagerFactory.createLdapInterface(getLdapInterfaceClassName()); ldapInterface.init(getLdapUrl(), getBaseDn(), getSearchBindDn(), getSearchBindPassword(), isFollowReferral(), isConnectionPooling(), null); // set the userDN when custom user search if (!StringUtils.isEmpty(getUserSearch())) { // customize the field used to search the user. SearchResult sr = ldapInterface.searchOneEntry(getUserSearch(), new String[] { "dn" }, SearchControls.SUBTREE_SCOPE); if (sr == null) { log.info("Username " + username + " not found"); return false; } userDN = sr.getNameInNamespace().trim(); log.info("binding with dn:" + userDN); } // on failure, set the user DN with append if (userDN == null) { userDN = "uid=" + username + "," + baseDn; } } catch (Exception e) { log.error("Can't instantiate LdapInterface: " + e.getMessage()); return false; } // Set up environment for creating initial context Hashtable<String, String> env = new Hashtable<String, String>(11); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, getLdapUrl()); // Authenticate as User and password env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, userDN); env.put(Context.SECURITY_CREDENTIALS, password); try { DirContext ctx = new InitialDirContext(env); log.debug(ctx.lookup(userDN)); ctx.close(); } catch (AuthenticationException e) { log.info("User not authenticated: " + e.getMessage()); return false; } catch (NamingException e) { log.warn("User not authenticated: problem while accessing ldap " + e.getMessage()); e.printStackTrace(); return false; } return true; }
From source file:de.sub.goobi.helper.ldap.Ldap.java
private Hashtable<String, String> getLdapConnectionSettings() { // Set up environment for creating initial context Hashtable<String, String> env = new Hashtable<>(11); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, ConfigCore.getParameter("ldap_url")); env.put(Context.SECURITY_AUTHENTICATION, "simple"); /* wenn die Verbindung ber ssl laufen soll */ if (ConfigCore.getBooleanParameter("ldap_sslconnection")) { String keystorepath = ConfigCore.getParameter("ldap_keystore"); String keystorepasswd = ConfigCore.getParameter("ldap_keystore_password"); // add all necessary certificates first loadCertificates(keystorepath, keystorepasswd); // set properties, so that the current keystore is used for SSL System.setProperty("javax.net.ssl.keyStore", keystorepath); System.setProperty("javax.net.ssl.trustStore", keystorepath); System.setProperty("javax.net.ssl.keyStorePassword", keystorepasswd); env.put(Context.SECURITY_PROTOCOL, "ssl"); }//from ww w . j a v a2 s . c o m return env; }
From source file:com.adito.activedirectory.ActiveDirectoryUserDatabaseConfiguration.java
InitialLdapContext getAuthenticatedContext(String url, Map<String, String> properties) throws NamingException { Hashtable<String, String> variables = new Hashtable<String, String>(properties); variables.put(Context.SECURITY_AUTHENTICATION, getServiceAuthenticationType()); if (!isServiceAuthenticationGssApi()) { variables.put(Context.SECURITY_PRINCIPAL, getServiceAccountName()); variables.put(Context.SECURITY_CREDENTIALS, getServiceAccountPassword()); }// ww w.j ava 2 s .co m return getInitialContext(url, variables); }
From source file:com.funambol.LDAP.security.LDAPUserProvisioningOfficer.java
/** * return the user dn of an ldap entry//from www .j a v a2s. c o m * * search: base, filter, attrs, user, pass * @return */ protected SearchResult ldapSearch(String bindUser, String bindPass, String base, String filter, String[] attributes) { SearchResult ret = null; Hashtable<String, Object> bindEnv = new Hashtable<String, Object>(11); bindEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); bindEnv.put(Context.PROVIDER_URL, getLdapUrl()); // remove null attributes List<String> goodAttributes = new ArrayList<String>(); for (String s : attributes) { if (s != null) { goodAttributes.add(s); } } // get the DN DirContext authenticationContext; try { SearchControls ctls = new SearchControls(); ctls.setCountLimit(1); ctls.setReturningObjFlag(true); ctls.setReturningAttributes(goodAttributes.toArray(new String[0])); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); // Authenticate as User and password if (bindUser != null && bindPass != null) { log.debug("NBinding with credential as user: " + bindUser); bindEnv.put(Context.SECURITY_AUTHENTICATION, "simple"); bindEnv.put(Context.SECURITY_PRINCIPAL, bindUser); bindEnv.put(Context.SECURITY_CREDENTIALS, bindPass); } authenticationContext = new InitialDirContext(bindEnv); // %u, %d in baseDN are still expanded NamingEnumeration<SearchResult> answer; try { answer = authenticationContext.search(base, filter, ctls); if (answer.hasMore()) { ret = (SearchResult) answer.next(); } } catch (NamingException e) { log.warn("Error while searching user with filter [" + filter + "]: " + e.getMessage()); } authenticationContext.close(); return ret; } catch (NamingException e) { log.error("Error while creating context: " + e.getMessage()); if (e.getCause() != null) { log.error("Error is: " + e.getCause().getMessage()); } return null; } }
From source file:com.dtolabs.rundeck.jetty.jaas.JettyCachingLdapLoginModule.java
/** * get the context for connection//from w ww .jav a2 s . c o m * * @return */ @SuppressWarnings("unchecked") public Hashtable getEnvironment() { Properties env = new Properties(); env.put(Context.INITIAL_CONTEXT_FACTORY, _contextFactory); String url = null; if (_providerUrl != null) { url = _providerUrl; } else { if (_hostname != null) { url = "ldap://" + _hostname + "/"; if (_port != 0) { url += ":" + _port + "/"; } LOG.warn("Using hostname and port. Use providerUrl instead: " + url); } } env.put(Context.PROVIDER_URL, url); if (_authenticationMethod != null) { env.put(Context.SECURITY_AUTHENTICATION, _authenticationMethod); } if (_bindDn != null) { env.put(Context.SECURITY_PRINCIPAL, _bindDn); } if (_bindPassword != null) { env.put(Context.SECURITY_CREDENTIALS, _bindPassword); } env.put("com.sun.jndi.ldap.read.timeout", Long.toString(_timeoutRead)); env.put("com.sun.jndi.ldap.connect.timeout", Long.toString(_timeoutConnect)); // Set the SSLContextFactory to implementation that validates cert subject if (url != null && url.startsWith("ldaps") && _ldapsVerifyHostname) { try { URI uri = new URI(url); HostnameVerifyingSSLSocketFactory.setTargetHost(uri.getHost()); env.put("java.naming.ldap.factory.socket", "com.dtolabs.rundeck.jetty.jaas.HostnameVerifyingSSLSocketFactory"); } catch (URISyntaxException e) { throw new RuntimeException(e); } } return env; }