protected void close(DirContext context) { try { context.close(); } catch (Exception e) { ActiveMQServerLogger.LOGGER.error(e.toString()); } }
public void addUser( Hashtable ldapEnv, String mail, String givenName, String sn, String cn, String userPassword) { Attributes attributes = new BasicAttributes(true); attributes.put(new BasicAttribute("mail", mail)); attributes.put(new BasicAttribute("objectClass", "inetOrgPerson")); // attributes.put(new BasicAttribute("objectClass","simpleSecurityObject")); attributes.put(new BasicAttribute("givenName", givenName)); attributes.put(new BasicAttribute("sn", sn)); attributes.put(new BasicAttribute("cn", cn)); attributes.put(new BasicAttribute("userPassword", userPassword)); DirContext ldapContext = null; try { ldapContext = new InitialDirContext(ldapEnv); // MonObjet objet = new MonObjet("valeur1","valeur2"); ldapContext.bind( "cn=" + cn + "," + Play.configuration.getProperty("ldap.dn"), null, attributes); ldapContext.close(); } catch (Exception e) { System.err.println("Erreur lors de l'acces au serveur LDAP " + e); e.printStackTrace(); } System.out.println("fin des traitements"); }
/** Search criteria based on sn(surname) */ private void searchUsingSubTree() { System.out.println("Inside searchUsingSubTree"); DirContext ctx = LDAPConstants.getLdapContext(); String baseDN = "OU=Staff,OU=Accounts,O=ibo,DC=adld,DC=ibo,DC=org"; SearchControls sc = new SearchControls(); String[] attributeFilter = {"cn", "givenName"}; sc.setReturningAttributes(attributeFilter); sc.setSearchScope(SearchControls.SUBTREE_SCOPE); String filter = "sn=X*"; // String filter = "(&(sn=R*)(givenName=Sinduja))"; //Examples for search Filters // String filter = "(|(sn=R*)(givenName=Sinduja))"; NamingEnumeration results = null; try { results = ctx.search(baseDN, filter, sc); while (results.hasMore()) { SearchResult sr = (SearchResult) results.next(); Attributes attrs = sr.getAttributes(); Attribute attr = attrs.get("cn"); System.out.print("cn : " + attr.get() + "\n"); attr = attrs.get("givenName"); System.out.print("givenName: " + attr.get() + "\n"); ctx.close(); } } catch (NamingException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
private void closeQuietly(DirContext context) { try { if (context != null) context.close(); } catch (NamingException e) { LOGGER.log(Level.INFO, "Failed to close DirContext: " + context, e); } }
public UserDTO doLdapAuthentication(UserDTO dto) throws Exception { log.info("INSIDE LDAP AUTHENTICATION 2"); UserDTO ldapDTO = null; String url = "ldap://172.18.20.0:10389"; Hashtable<String, String> env = new Hashtable<String, String>(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, url); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system"); env.put(Context.SECURITY_CREDENTIALS, "secret"); try { ldapDTO = new UserDTO(); DirContext ctx = new InitialDirContext(env); Attributes attrs = ctx.getAttributes("cn=" + dto.getUsername() + ",ou=users,ou=system"); Attribute userPassword = attrs.get("userPassword"); String ldapPasswordFromDB = new String((byte[]) userPassword.get()); String md5EncryptedPassword = encryptLdapPassword("md5", dto.getPassword()); if (md5EncryptedPassword.equalsIgnoreCase(ldapPasswordFromDB)) { ldapDTO.setEmployeeId((String) (attrs.get("employeeNumber").get())); ldapDTO.setEmployeeType((String) (attrs.get("employeeType").get())); ldapDTO.setUsername((String) (attrs.get("cn").get())); } ctx.close(); } catch (Exception e) { e.printStackTrace(); } return ldapDTO; }
private void searchUsingObject() { System.out.println("Inside searchUsingObject"); DirContext ctx = LDAPConstants.getLdapContext(); // String baseDN = "CN=sindujar,OU=Staff,OU=Accounts,O=ibo,DC=adld,DC=ibo,DC=org"; //To serach // for a particular user String baseDN = "OU=Staff,OU=Accounts,O=ibo,DC=adld,DC=ibo,DC=org"; SearchControls sc = new SearchControls(); sc.setSearchScope(SearchControls.SUBTREE_SCOPE); String filter = "objectclass=*"; // String filter = "(&(sn=R*)(givenName=Sinduja))"; //Examples for search Filters // String filter = "(|(sn=R*)(givenName=Sinduja))"; NamingEnumeration results = null; try { results = ctx.search(baseDN, filter, sc); while (results.hasMore()) { SearchResult sr = (SearchResult) results.next(); System.out.println(sr.toString() + "\n"); ctx.close(); } } catch (NamingException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
// 关闭到LDAP服务器的连接 private void closeConnection() { try { ctx.close(); } catch (NamingException ne) { System.out.println(ne); } }
public static void main(String[] args) { // Set up environment for creating initial context Hashtable<String, Object> env = new Hashtable<String, Object>(11); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial"); // Authenticate as S. User and password "mysecret" env.put(Context.SECURITY_AUTHENTICATION, "custom"); env.put(Context.SECURITY_PRINCIPAL, "cn=S. User, ou=NewHires, o=JNDITutorial"); env.put(Context.SECURITY_CREDENTIALS, "mysecret"); try { // Create initial context DirContext ctx = new InitialDirContext(env); System.out.println(ctx.lookup("ou=NewHires")); // do something useful with ctx // Close the context when we're done ctx.close(); } catch (NamingException e) { e.printStackTrace(); } }
void addGroup(Hashtable<String, String> ldapEnv, String cn, ArrayList members, String owner) { Attributes attributes = new BasicAttributes(true); attributes.put(new BasicAttribute("objectClass", "groupOfNames")); attributes.put(new BasicAttribute("cn", cn)); attributes.put( new BasicAttribute( "owner", "cn=" + owner + "," + Play.configuration.getProperty("ldap.dn"))); Iterator memberIterator = members.iterator(); BasicAttribute membersAttribute = new BasicAttribute( "member", "cn=" + owner + "," + Play.configuration.getProperty("ldap.dn")); while (memberIterator.hasNext()) { String specificMember = "cn=" + memberIterator.next() + "," + Play.configuration.getProperty("ldap.dn"); if (!membersAttribute.contains(specificMember)) membersAttribute.add(specificMember); } attributes.put(membersAttribute); DirContext ldapContext = null; try { ldapContext = new InitialDirContext(ldapEnv); ldapContext.bind( "cn=" + cn + "," + Play.configuration.getProperty("ldap.dn"), null, attributes); ldapContext.close(); } catch (Exception e) { System.err.println("Erreur lors de l'acces au serveur LDAP " + e); e.printStackTrace(); } System.out.println("fin des traitements"); }
public DirContext getSchemaClassDefinition(String name) throws NamingException { ResolveResult res = getRootURLContext(name, myEnv); DirContext ctx = (DirContext) res.getResolvedObj(); try { return ctx.getSchemaClassDefinition(res.getRemainingName()); } finally { ctx.close(); } }
public DirContext createSubcontext(String name, Attributes attrs) throws NamingException { ResolveResult res = getRootURLContext(name, myEnv); DirContext ctx = (DirContext) res.getResolvedObj(); try { return ctx.createSubcontext(res.getRemainingName(), attrs); } finally { ctx.close(); } }
public void rebind(String name, Object obj, Attributes attrs) throws NamingException { ResolveResult res = getRootURLContext(name, myEnv); DirContext ctx = (DirContext) res.getResolvedObj(); try { ctx.rebind(res.getRemainingName(), obj, attrs); } finally { ctx.close(); } }
public Attributes getAttributes(String name, String[] attrIds) throws NamingException { ResolveResult res = getRootURLContext(name, myEnv); DirContext ctx = (DirContext) res.getResolvedObj(); try { return ctx.getAttributes(res.getRemainingName(), attrIds); } finally { ctx.close(); } }
/** * Returns a list of AD Groups using the service account * * @return list of AD Groups */ public static List<String> getADGroupsByServiceAccount() { String username = MessageUtils.getMessage("ldap.service.account.username"); String password = MessageUtils.getMessage("ldap.service.account.password"); List<String> awsAllGroups = null; logger.debug("Starting....."); if (username == null || password == null) { return new ArrayList<String>(); } Hashtable<String, String> env = new Hashtable<String, String>(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, MessageUtils.getMessage("ldap.service.account.url")); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, username); env.put(Context.SECURITY_CREDENTIALS, password); DirContext ctx = null; try { logger.debug("Getting AWS groups using service account"); ctx = new InitialDirContext(env); logger.debug("After InitialDirContext"); SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); String attr[] = {"samaccountname"}; controls.setReturningAttributes(attr); NamingEnumeration<SearchResult> result = ctx.search( MessageUtils.getMessage("ldap.service.account.conf.name"), MessageUtils.getMessage("ldap.service.account.conf.filter"), controls); awsAllGroups = new ArrayList<String>(); SearchResult sr = null; // Loop through the search results while (result.hasMoreElements()) { sr = (SearchResult) result.next(); awsAllGroups.add(sr.getName().substring(3)); } return awsAllGroups; } catch (AuthenticationException e) { logger.error("Service account details are not correct." + e.getMessage()); return null; } catch (NamingException e) { logger.error("Unable to connect" + e.getMessage()); return new ArrayList<String>(); } finally { if (ctx != null) { try { ctx.close(); } catch (NamingException e) { } } } }
public void modifyAttributes(String name, int mod_op, Attributes attrs) throws NamingException { ResolveResult res = getRootURLContext(name, myEnv); DirContext ctx = (DirContext) res.getResolvedObj(); try { ctx.modifyAttributes(res.getRemainingName(), mod_op, attrs); } finally { ctx.close(); } }
protected void closeDirContext(DirContext dirContext) { if (dirContext != null) { try { dirContext.close(); } catch (NamingException e) { // Not fatal since we're just trying to close a connection } } }
/** * @see net.jforum.sso.LoginAuthenticator#validateLogin(java.lang.String, java.lang.String, * java.util.Map) */ public User validateLogin(String username, String password, Map extraParams) { Hashtable environment = this.prepareEnvironment(); StringBuffer principal = new StringBuffer(256) .append(SystemGlobals.getValue(ConfigKeys.LDAP_LOGIN_PREFIX)) .append(username) .append(',') .append(SystemGlobals.getValue(ConfigKeys.LDAP_LOGIN_SUFFIX)); environment.put(Context.SECURITY_PRINCIPAL, principal.toString()); environment.put(Context.SECURITY_CREDENTIALS, password); DirContext dir = null; try { dir = new InitialDirContext(environment); String lookupPrefix = SystemGlobals.getValue(ConfigKeys.LDAP_LOOKUP_PREFIX); String lookupSuffix = SystemGlobals.getValue(ConfigKeys.LDAP_LOOKUP_SUFFIX); if (lookupPrefix == null || lookupPrefix.length() == 0) { lookupPrefix = SystemGlobals.getValue(ConfigKeys.LDAP_LOGIN_PREFIX); } if (lookupSuffix == null || lookupSuffix.length() == 0) { lookupSuffix = SystemGlobals.getValue(ConfigKeys.LDAP_LOGIN_SUFFIX); } String lookupPrincipal = lookupPrefix + username + "," + lookupSuffix; Attribute att = dir.getAttributes(lookupPrincipal) .get(SystemGlobals.getValue(ConfigKeys.LDAP_FIELD_EMAIL)); SSOUtils utils = new SSOUtils(); if (!utils.userExists(username)) { String email = att != null ? (String) att.get() : "noemail"; utils.register("ldap", email); } return utils.getUser(); } catch (AuthenticationException e) { return null; } catch (NamingException e) { return null; } finally { if (dir != null) { try { dir.close(); } catch (NamingException e) { // close jndi context } } } }
@Test public void testMissingProviderUrlLdapSearches() throws NamingException { DirContext context = new TestLdapContext(new Hashtable<Object, Object>()); try { runNonLdapSearchControlsActions(context); } finally { context.close(); } }
/** Disconnect from the server. */ public void disconnect() { try { if (dirContext != null) { dirContext.close(); dirContext = null; } } catch (NamingException e) { log.error("Ldap client - ", e); } }
public NamingEnumeration<SearchResult> search(String name, Attributes matchingAttributes) throws NamingException { ResolveResult res = getRootURLContext(name, myEnv); DirContext ctx = (DirContext) res.getResolvedObj(); try { return ctx.search(res.getRemainingName(), matchingAttributes); } finally { ctx.close(); } }
public NamingEnumeration<SearchResult> search(String name, String filter, SearchControls cons) throws NamingException { ResolveResult res = getRootURLContext(name, myEnv); DirContext ctx = (DirContext) res.getResolvedObj(); try { return ctx.search(res.getRemainingName(), filter, cons); } finally { ctx.close(); } }
public LDAPInfo lookUp(String username, String password) { try { String uidFilter = "(" + uidAttr + "=" + username + ")"; String usersBaseDN = usersDN + "," + baseDN; String path = null; try { path = LDAPUtil.findUserDN(getUrl(), uidFilter, usersBaseDN); } catch (NamingException ex) { Log.warning(Geonet.LDAP, ex.getMessage()); } if (path == null || path.length() == 0) { path = uidAttr + "=" + username + "," + usersDN + "," + baseDN; } DirContext dc = LDAPUtil.openContext(getUrl(), path, password); Map<String, ? extends List<Object>> attr = LDAPUtil.getNodeInfo(dc, path); dc.close(); if (attr == null) { Log.warning(Geonet.LDAP, "Username not found :'" + username + "'"); return null; } else { LDAPInfo info = new LDAPInfo(); info.username = username; info.password = password; info.name = get(attr, nameAttr); info.profile = (profileAttr == null) ? defProfile : get(attr, profileAttr); if (info.profile.equals("Reviewer")) { info.profile = "Hoofdeditor"; } info.email = get(attr, emailAttr); info.groups = (groupAttr == null) ? new String[] {defGroup} : getAll(attr, groupAttr); if (!profiles.contains(info.profile)) { Log.warning(Geonet.LDAP, "Skipping user with unknown profile"); Log.warning(Geonet.LDAP, " (C) Username :'******'"); Log.warning(Geonet.LDAP, " (C) Profile :'" + info.profile + "'"); return null; } return info; } } catch (NamingException e) { Log.warning(Geonet.LDAP, "Raised exception during LDAP access"); Log.warning(Geonet.LDAP, " (C) Message :" + e.getMessage()); return null; } }
public List<Roles> getRoles(Roles roles) { LOG.info("Inside getRoles"); List<Roles> rolesList = new ArrayList<Roles>(); DirContext ctx = LDAPConstants.getLdapContext(); String baseDN = PropertyFileReader.getProperty(IAMApplicationConstants.BASEDN_ROLES); SearchControls sc = new SearchControls(); sc.setSearchScope(SearchControls.SUBTREE_SCOPE); String retAttrs[] = { "whenCreated", "whenChanged", "cn", "name", "distinguishedName", "groupType", "ibRolesName", "ibRolesAppSelection", "ibRolesOwner", "ibRolesIsIBIS", "ibRolesReqBy", "ibRolesBusArea", "ibRolesStartDate", "ibRolesType", "ibRolesIsOwner", "ibRolesAuthBy", "ibRolesDescription", "member", "ibRolesStatus", "ibRolesCode", "ibRolesEndDate", "ibRolesCVReq" }; sc.setReturningAttributes(retAttrs); String filter = buildFilter(roles); LOG.info("Filter--" + filter); NamingEnumeration results = null; try { results = ctx.search(baseDN, filter, sc); while (results.hasMore()) { SearchResult sr = (SearchResult) results.next(); Attributes attrs = sr.getAttributes(); NamingEnumeration e = attrs.getAll(); Roles ioRoles = new Roles(); while (e.hasMoreElements()) { Attribute attr = (Attribute) e.nextElement(); ioRoles = (Roles) getResults(attr, ioRoles); } rolesList.add(ioRoles); } ctx.close(); } catch (NamingException e) { e.printStackTrace(); } return rolesList; }
/* (non-Javadoc) * @see jrds.Starter#stop() */ @Override public void stopConnection() { uptime = 1; if (dctx != null) try { dctx.close(); } catch (NamingException e) { log(Level.ERROR, e, "Error close to %s, cause: %s", getLevel(), e.getCause()); } dctx = null; }
public boolean authenticate(String uid, String passwd) throws DataSourceException, ConfigException { try { String providerUrl = source.getProviderUrl() + "/" + source.getBaseDn(); DirContext ctxtDir = null; if (!source.isActiveDirectory()) { String dn = source.getUsersDn(); if (dn != null && dn.indexOf(':') == -1) { // single CN ctxtDir = this.getContext( providerUrl, source.getAuthenticationMode(), source.getReferralMode(), getUserString(uid), passwd); } else { // multiple CN String[] ns = dn.split(":"); for (int i = 0; i < ns.length; i++) { try { ctxtDir = this.getContext( providerUrl, source.getAuthenticationMode(), source.getReferralMode(), source.getUsersIdKey() + "=" + uid + "," + ns[i], passwd); break; } catch (javax.naming.AuthenticationException ae) { continue; } } } } else { ctxtDir = this.getContext( providerUrl, source.getAuthenticationMode(), source.getReferralMode(), getUserString(uid), passwd); } if (ctxtDir != null) { ctxtDir.close(); } return true; } catch (javax.naming.AuthenticationException e) { return false; } catch (NamingException e) { throw new DataSourceException(e, "LDAP Exception : " + e.getMessage()); } }
public DirContext createSubcontext(Name name, Attributes attrs) throws NamingException { if (name.size() == 1) { return createSubcontext(name.get(0), attrs); } else { DirContext ctx = getContinuationDirContext(name); try { return ctx.createSubcontext(name.getSuffix(1), attrs); } finally { ctx.close(); } } }
public DirContext getSchemaClassDefinition(Name name) throws NamingException { if (name.size() == 1) { return getSchemaClassDefinition(name.get(0)); } else { DirContext ctx = getContinuationDirContext(name); try { return ctx.getSchemaClassDefinition(name.getSuffix(1)); } finally { ctx.close(); } } }
/** disconnect from the server */ public static void disconnect(DirContext dirContext) { if (dirContext == null) { log.info("Cannot disconnect null context"); return; } try { dirContext.close(); } catch (NamingException e) { log.warn("Ldap client disconnect - ", e); } }
/** * Load an Ldif file into an LDAP server. * * @param contextSource ContextSource to use for getting a DirContext to interact with the LDAP * server. * @param ldifFile a Resource representing a valid LDIF file. * @throws IOException if the Resource cannot be read. */ public static void loadLdif(ContextSource contextSource, Resource ldifFile) throws IOException { DirContext context = contextSource.getReadWriteContext(); try { loadLdif(context, ldifFile); } finally { try { context.close(); } catch (Exception e) { // This is not the exception we are interested in. } } }
public Attributes getAttributes(Name name, String[] attrIds) throws NamingException { if (name.size() == 1) { return getAttributes(name.get(0), attrIds); } else { DirContext ctx = getContinuationDirContext(name); try { return ctx.getAttributes(name.getSuffix(1), attrIds); } finally { ctx.close(); } } }