List of usage examples for javax.naming.directory InitialDirContext InitialDirContext
public InitialDirContext(Hashtable<?, ?> environment) throws NamingException
From source file:pl.umk.mat.zawodyweb.ldap.LdapConnector.java
/** * Check user password and return that user * * Example of LDAP data:/*from w w w . j a v a2s .c o m*/ * <pre> * dn: uid=faramir,ou=People,ou=int,dc=mat,dc=uni,dc=torun,dc=pl * objectClass: top * objectClass: account * objectClass: posixAccount * objectClass: shadowAccount * objectClass: radiusprofile * objectClass: sambaSamAccount * dialupAccess: yes * uid: faramir * cn: Marek Nowicki * loginShell: /bin/tcsh * uidNumber: 30030 * sambaSID: S-1-30030 * gecos: Marek Nowicki, doktorant Info. * gidNumber: 160 * homeDirectory: /studdok/faramir * radiusSimultaneousUse: 1</pre> * @param login login * @param pass user password * @return Users if user found and password is OK or null if anything failed */ public static Users retieveUser(String login, String pass) { if (pass == null || pass.isEmpty() || login == null || login.isEmpty() || login.contains(",")) { return null; } Hashtable<String, String> ldapEnv = new Hashtable<String, String>(11); String dn = String.format("uid=%s,%s", login, baseDN); ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); ldapEnv.put(Context.PROVIDER_URL, ldapURL); ldapEnv.put(Context.SECURITY_PRINCIPAL, dn); ldapEnv.put(Context.SECURITY_CREDENTIALS, pass); try { DirContext authContext = new InitialDirContext(ldapEnv); Attributes userAttributes = authContext.getAttributes(dn); if (userAttributes.get("uidNumber") == null) { return null; } Attribute cn = userAttributes.get("cn"); // commonName - eg. Marek Nowicki String name = ((String) cn.get()); String firstName = name; String lastName = "(LDAP)"; int index = name.lastIndexOf(" "); if (index > 0) { firstName = name.substring(0, index).trim(); lastName = name.substring(index + 1).trim(); } Users user = new Users(); user.setLogin(login); user.setFirstname(firstName); user.setLastname(lastName); user.setEmail(login + emailSuffix); return user; } catch (AuthenticationException ex) { } catch (NamingException ex) { } catch (NullPointerException ex) { } catch (ClassCastException ex) { } catch (Exception ex) { log.fatal("LDAP Exception:", ex); } return null; }
From source file:it.infn.ct.security.utilities.LDAPUtils.java
private static DirContext getContext() throws NamingException { ResourceBundle rb = ResourceBundle.getBundle("ldap"); Properties env = new Properties(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, rb.getString("url")); env.put(Context.SECURITY_PRINCIPAL, rb.getString("rootDN")); env.put(Context.SECURITY_AUTHENTICATION, "none"); return new InitialDirContext(env); }
From source file:org.eclipselabs.etrack.util.security.ldap.impl.LdapSecurityService.java
@Override public boolean authenticate(String id, char[] password) { String cachedPassword = credentialCache.get(id); String encodedPassword = null; try {/*from ww w.j a v a 2 s .co m*/ encodedPassword = codec.encode(new String(password)); } catch (EncoderException e1) { } if (cachedPassword != null && encodedPassword != null && cachedPassword.equals(encodedPassword)) return true; Hashtable<String, String> environment = new Hashtable<String, String>(); environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); environment.put(Context.PROVIDER_URL, url); environment.put(Context.SECURITY_AUTHENTICATION, "simple"); environment.put(Context.SECURITY_PRINCIPAL, id); environment.put(Context.SECURITY_CREDENTIALS, new String(password)); try { InitialDirContext context = new InitialDirContext(environment); context.close(); if (encodedPassword != null) credentialCache.put(id, encodedPassword); return true; } catch (NamingException e) { return false; } }
From source file:org.wso2.carbon.connector.ldap.LDAPUtils.java
protected static DirContext getDirectoryContext(MessageContext messageContext) throws NamingException { String providerUrl = LDAPUtils.lookupContextParams(messageContext, LDAPConstants.PROVIDER_URL); String securityPrincipal = LDAPUtils.lookupContextParams(messageContext, LDAPConstants.SECURITY_PRINCIPAL); String securityCredentials = LDAPUtils.lookupContextParams(messageContext, LDAPConstants.SECURITY_CREDENTIALS); boolean secureConnection = Boolean .valueOf(LDAPUtils.lookupContextParams(messageContext, LDAPConstants.SECURE_CONNECTION)); boolean disableSSLCertificateChecking = Boolean .valueOf(LDAPUtils.lookupContextParams(messageContext, LDAPConstants.DISABLE_SSL_CERT_CHECKING)); Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, LDAPConstants.COM_SUN_JNDI_LDAP_LDAPCTXFACTORY); env.put(Context.PROVIDER_URL, providerUrl); env.put(Context.SECURITY_PRINCIPAL, securityPrincipal); env.put(Context.SECURITY_CREDENTIALS, securityCredentials); if (secureConnection) { env.put(Context.SECURITY_PROTOCOL, LDAPConstants.SSL); }//from w w w. j a va 2s .c om if (disableSSLCertificateChecking) { env.put(LDAPConstants.JAVA_NAMING_LDAP_FACTORY_SOCKET, LDAPConstants.ORG_WSO2_CARBON_CONNECTOR_SECURITY_MYSSLSOCKETFACTORY); } DirContext ctx = null; ctx = new InitialDirContext(env); return ctx; }
From source file:org.eclipselabs.etrack.util.security.ldap.impl.LdapService.java
@Override public boolean authenticate(String id, char[] password) { if (id == null || id.isEmpty()) return false; if (idSuffix != null) id = id + idSuffix;// ww w . ja v a 2s . c o m String cachedPassword = credentialCache.get(id); String encodedPassword = null; try { encodedPassword = codec.encode(new String(password)); } catch (EncoderException e1) { } if (cachedPassword != null && encodedPassword != null && cachedPassword.equals(encodedPassword)) return true; Hashtable<String, String> environment = new Hashtable<String, String>(); environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); environment.put(Context.PROVIDER_URL, url); environment.put(Context.SECURITY_AUTHENTICATION, "simple"); environment.put(Context.SECURITY_PRINCIPAL, id); environment.put(Context.SECURITY_CREDENTIALS, new String(password)); try { InitialDirContext context = new InitialDirContext(environment); context.close(); if (encodedPassword != null) credentialCache.put(id, encodedPassword); return true; } catch (NamingException e) { return false; } }
From source file:security.AuthenticationManager.java
public static void authenticateUser(String userName, String password) throws NamingException, SQLException { if (userName == null || userName.isEmpty() || password == null || password.isEmpty()) { throw new IllegalArgumentException("Username and password can not be blank."); }/*from w ww.j a va2 s .c om*/ if (UserDAO.authenticate(userName, password)) { UserDAO.insertLoginHistory(userName, "default", "SUCCESS", null); return; } final String contextFactories = Play.application().configuration() .getString(LDAP_CONTEXT_FACTORY_CLASS_KEY); /* three LDAP properties, each is a '|' separated string of same number of tokens. e.g. Url: "ldaps://ldap1.abc.com:1234|ldap://ldap2.abc.com:5678" Principal Domain: "@abc.com|@abc.cn" Search Base: "ou=Staff Users,dc=abc,dc=com|ou=Staff Users,dc=abc,dc=cn" */ final String[] ldapUrls = Play.application().configuration().getString(MASTER_LDAP_URL_KEY) .split("\\s*\\|\\s*"); final String[] principalDomains = Play.application().configuration().getString(MASTER_PRINCIPAL_DOMAIN_KEY) .split("\\s*\\|\\s*"); final String[] ldapSearchBase = Play.application().configuration().getString(LDAP_SEARCH_BASE_KEY) .split("\\s*\\|\\s*"); DirContext ctx = null; int i; for (i = 0; i < ldapUrls.length; i++) { try { Hashtable<String, String> env = buildEnvContext(userName, password, contextFactories, ldapUrls[i], principalDomains[i]); ctx = new InitialDirContext(env); if (!UserDAO.userExist(userName)) { User user = getAttributes(ctx, ldapSearchBase[i], userName, principalDomains[i]); UserDAO.addLdapUser(user); } break; } catch (NamingException e) { // Logger.error("Ldap authentication failed for user " + userName + " - " + principalDomains[i] + " - " + ldapUrls[i], e); // if exhausted all ldap options and can't authenticate user if (i >= ldapUrls.length - 1) { UserDAO.insertLoginHistory(userName, "LDAP", "FAILURE", e.getMessage()); throw e; } } catch (SQLException e) { // Logger.error("Ldap authentication SQL error for user: " + userName, e); UserDAO.insertLoginHistory(userName, "LDAP", "FAILURE", ldapUrls[i] + e.getMessage()); throw e; } finally { if (ctx != null) { ctx.close(); } } } UserDAO.insertLoginHistory(userName, "LDAP", "SUCCESS", ldapUrls[i]); }
From source file:io.apiman.gateway.engine.policies.auth.LDAPIdentityValidator.java
/** * @see io.apiman.gateway.engine.policies.auth.IIdentityValidator#validate(java.lang.String, java.lang.String, io.apiman.gateway.engine.beans.ServiceRequest, io.apiman.gateway.engine.policy.IPolicyContext, java.lang.Object, io.apiman.gateway.engine.async.IAsyncHandler) *//*from w w w.j a v a2 s .co m*/ @Override public void validate(String username, String password, ServiceRequest request, IPolicyContext context, LDAPIdentitySource config, IAsyncResultHandler<Boolean> handler) { String url = config.getUrl(); String dn = formatDn(config.getDnPattern(), username, request); Hashtable<String, String> env = new Hashtable<String, String>(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); //$NON-NLS-1$ env.put(Context.PROVIDER_URL, url); env.put(Context.SECURITY_AUTHENTICATION, "simple"); //$NON-NLS-1$ env.put(Context.SECURITY_PRINCIPAL, dn); env.put(Context.SECURITY_CREDENTIALS, password); try { new InitialDirContext(env); handler.handle(AsyncResultImpl.create(Boolean.TRUE)); } catch (AuthenticationException e) { handler.handle(AsyncResultImpl.create(Boolean.FALSE)); } catch (NamingException e) { throw new RuntimeException(e); } }
From source file:com.jaeksoft.searchlib.util.ActiveDirectory.java
public ActiveDirectory(String username, String password, String domain) throws NamingException { if (StringUtils.isEmpty(domain)) throw new NamingException("The domain is empty"); Properties properties = new Properties(); properties.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); properties.put(Context.PROVIDER_URL, StringUtils.fastConcat("LDAP://", domain)); properties.put(Context.SECURITY_PRINCIPAL, StringUtils.fastConcat(username, "@", domain)); properties.put(Context.SECURITY_CREDENTIALS, password); properties.put("java.naming.ldap.attributes.binary", "objectSID"); properties.put(Context.REFERRAL, "follow"); dirContext = new InitialDirContext(properties); domainSearchName = getDomainSearch(domain); }
From source file:org.malaguna.cmdit.service.ldap.LDAPBase.java
public Attributes loadUser(String uid, String[] attrs) { // Preparar las variables de entorno para la conexin JNDI Hashtable<String, String> entorno = new Hashtable<String, String>(); // Credenciales del usuario para realizar la bsqueda String cadena = "uid=" + user + "," + context; entorno.put(Context.PROVIDER_URL, server); entorno.put(Context.INITIAL_CONTEXT_FACTORY, initContext); if (password != null && user != null) { entorno.put(Context.SECURITY_PRINCIPAL, cadena); entorno.put(Context.SECURITY_CREDENTIALS, password); }/*from w w w. j av a2 s .c om*/ Attributes atributos = null; try { // Crear contexto de directorio inicial DirContext ctx = new InitialDirContext(entorno); // Recuperar atributos del usuario que se est buscando if (attrs != null) atributos = ctx.getAttributes("uid=" + uid + "," + context, attrs); else atributos = ctx.getAttributes("uid=" + uid + "," + context); // Cerrar la conexion ctx.close(); } catch (NamingException e) { logger.error(messages.getMessage("err.ldap.attribute", new Object[] { e }, Locale.getDefault())); } return atributos; }
From source file:de.tuttas.util.LDAPUtil.java
/** * Benutzer aus der LDAP Abfragen//from ww w.j a va 2s . co m * * @param username Benutzername * @param password Kennwort * @return der Benutzer * @throws Exception Wenn etwas schief ging */ public LDAPUser authenticateJndi(String username, String password) throws Exception { // Anbindung ans LDAP Properties props = new Properties(); props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); props.put(Context.PROVIDER_URL, Config.getInstance().ldaphost); props.put(Context.SECURITY_PRINCIPAL, Config.getInstance().bindUser);//adminuser - User with special priviledge, dn user props.put(Context.SECURITY_CREDENTIALS, Config.getInstance().bindPassword);//dn user password try { context = new InitialDirContext(props); ctrls = new SearchControls(); ctrls.setReturningAttributes(new String[] { "description", "mail", "sn", "initials", "givenName", "memberOf", "userPrincipalName", "distinguishedName" }); ctrls.setSearchScope(SearchControls.SUBTREE_SCOPE); } catch (NamingException ex) { Logger.getLogger(LDAPUtil.class.getName()).log(Level.SEVERE, null, ex); } NamingEnumeration<javax.naming.directory.SearchResult> answers = context .search(Config.getInstance().userContext, "(cn=" + username + ")", ctrls); Log.d("answers=" + answers); Log.d("answers=" + answers.hasMore()); if (!answers.hasMore()) { return null; } javax.naming.directory.SearchResult result = answers.nextElement(); try { for (NamingEnumeration ae = result.getAttributes().getAll(); ae.hasMore();) { Attribute attr = (Attribute) ae.next(); Log.d("attribute: " + attr.getID()); /* print each value */ for (NamingEnumeration e = attr.getAll(); e.hasMore(); System.out.println("value: " + e.next())) ; } } catch (NamingException e) { e.printStackTrace(); } String inititials = ""; if (result.getAttributes().get("initials") != null) { inititials = result.getAttributes().get("initials").getAll().next().toString(); } LDAPUser u; if (result.getAttributes().get("mail") == null) { u = new LDAPUser(result.getAttributes().get("sn").getAll().next().toString(), result.getAttributes().get("givenName").getAll().next().toString(), "", inititials); } else { u = new LDAPUser(result.getAttributes().get("sn").getAll().next().toString(), result.getAttributes().get("givenName").getAll().next().toString(), result.getAttributes().get("mail").getAll().next().toString(), inititials); } String dName = result.getAttributes().get("distinguishedName").getAll().next().toString(); Log.d("dName=" + dName); if (dName.contains("OU=Lehrer")) { Log.d("Ich bin ein Lehrer"); u.setRole(Roles.toString(Roles.LEHRER)); } else { Log.d("Ich bin ein Schler"); u.setRole(Roles.toString(Roles.SCHUELER)); if (result.getAttributes().get("memberOf") != null) { String memberOf = result.getAttributes().get("memberOf").getAll().next().toString(); String courseName = memberOf.split(",")[0]; courseName = courseName.substring(courseName.indexOf("=") + 1); Log.d("Name der Klasse ist " + courseName); u.setCourse(courseName); } } String user = result.getNameInNamespace(); try { props = new Properties(); props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); props.put(Context.PROVIDER_URL, Config.getInstance().ldaphost); props.put(Context.SECURITY_PRINCIPAL, user); props.put(Context.SECURITY_CREDENTIALS, password); context = new InitialDirContext(props); } catch (Exception e) { return null; } return u; }