List of usage examples for javax.naming.directory DirContext getNameInNamespace
public String getNameInNamespace() throws NamingException;
From source file:org.cloudfoundry.identity.uaa.ldap.extension.SpringSecurityLdapTemplate.java
/** * Internal method extracted to avoid code duplication in AD search. *//* w w w. j a va 2s .c o m*/ public static DirContextOperations searchForSingleEntryInternal(DirContext ctx, SearchControls searchControls, String base, String filter, Object[] params) throws NamingException { final DistinguishedName ctxBaseDn = new DistinguishedName(ctx.getNameInNamespace()); final DistinguishedName searchBaseDn = new DistinguishedName(base); final NamingEnumeration<SearchResult> resultsEnum = ctx.search(searchBaseDn, filter, params, buildControls(searchControls)); if (logger.isDebugEnabled()) { logger.debug("Searching for entry under DN '" + ctxBaseDn + "', base = '" + searchBaseDn + "', filter = '" + filter + "'"); } Set<DirContextOperations> results = new HashSet<DirContextOperations>(); try { while (resultsEnum.hasMore()) { SearchResult searchResult = resultsEnum.next(); DirContextAdapter dca = (DirContextAdapter) searchResult.getObject(); Assert.notNull(dca, "No object returned by search, DirContext is not correctly configured"); if (logger.isDebugEnabled()) { logger.debug("Found DN: " + dca.getDn()); } results.add(dca); } } catch (PartialResultException e) { LdapUtils.closeEnumeration(resultsEnum); logger.info("Ignoring PartialResultException"); } if (results.size() == 0) { throw new IncorrectResultSizeDataAccessException(1, 0); } if (results.size() > 1) { throw new IncorrectResultSizeDataAccessException(1, results.size()); } return results.iterator().next(); }
From source file:org.gbif.portal.registration.LDAPUtils.java
/** * Creates a user. String array contains: * 1) first name/*from ww w . j a v a2 s . com*/ * 2) surname * 3) email * 4) username * 5) password * * @param userDetails * @return * @throws NamingException */ public boolean createNewUser(UserLogin userLogin) throws NamingException { DirContext ctx = getUserContext(); Attributes attributes = new BasicAttributes(); attributes.put(new BasicAttribute("sn", userLogin.getSurname())); attributes.put(new BasicAttribute("givenName", userLogin.getFirstName())); attributes.put(new BasicAttribute("cn", userLogin.getFirstName() + " " + userLogin.getSurname())); attributes.put(new BasicAttribute("mail", userLogin.getEmail())); if (userLogin.getTelephone() != null) { attributes.put(new BasicAttribute("telephoneNumber", userLogin.getTelephone())); } attributes.put(new BasicAttribute("userPassword", userLogin.getPassword())); attributes.put(new BasicAttribute("objectClass", "top")); attributes.put(new BasicAttribute("objectClass", "person")); attributes.put(new BasicAttribute("objectClass", "organizationalPerson")); attributes.put(new BasicAttribute("objectClass", "inetorgperson")); String contextName = "uid=" + userLogin.getUsername(); String fullContextName = contextName + "," + ctx.getNameInNamespace(); //add the user to ldap ctx.createSubcontext(contextName, attributes); //need to add user to group for (int i = 0; i < userGroups.length; i++) { DirContext groupContext = getGroupContext(); Attributes groupAttributes = groupContext.getAttributes(userGroups[i]); groupAttributes.get("uniqueMember").add(fullContextName); groupContext.modifyAttributes(userGroups[i], DirContext.REPLACE_ATTRIBUTE, groupAttributes); } return true; }
From source file:org.jkcsoft.java.util.JndiHelper.java
public static void logLdap(Log plog, int level, int nth, Object dirEntry) throws NamingException { try {/*from w ww .j a v a2s . co m*/ if (dirEntry instanceof NamingEnumeration) { NamingEnumeration nameEnum = (NamingEnumeration) dirEntry; JndiHelper.logLevel(plog, level, nth, "Naming Enumeration: " + nameEnum); try { int nthThis = 0; List nameList = new Vector(Collections.list(nameEnum)); Collections.sort(nameList, new Comparator() { public int compare(Object o1, Object o2) { if (o1 instanceof Attribute) { return String.CASE_INSENSITIVE_ORDER.compare(((Attribute) o1).getID(), ((Attribute) o2).getID()); } return 0; } }); Iterator nameIter = nameList.iterator(); while (nameIter.hasNext()) { logLdap(plog, level + 1, nthThis++, nameIter.next()); } } catch (NamingException ex) { plog.error("Exception iterating thru NamingEnumeration: " + ex.getMessage()); } } else if (dirEntry instanceof Attribute) { Attribute dirAttr = (Attribute) dirEntry; JndiHelper.logLevel(plog, level, nth, "Attribute: [" + dirAttr + "]"); } else if (dirEntry instanceof DirContext) { DirContext lctx = (DirContext) dirEntry; JndiHelper.logLevel(plog, level, nth, "LDAP Context: DN [" + lctx.getNameInNamespace() + "]" + " Attributes ==>"); logLdap(plog, level, nth, lctx.getAttributes("").getAll()); } else if (dirEntry instanceof SearchResult) { SearchResult sr = (SearchResult) dirEntry; JndiHelper.logLevel(plog, level, nth, "SearchResult: ClassName of Bound Object [" + sr.getClassName() + "]" + " Name: [" + sr.getName() + "]" + " Bound Object ==>"); // sr.s logLdap(plog, level, nth, sr.getObject()); logLdap(plog, level, nth, sr.getAttributes().getAll()); } else { JndiHelper.logLevel(plog, level, nth, "(?) class of entry: [" + dirEntry + "]"); } nth++; } catch (NamingException e1) { plog.error("Naming Exception (will try to continue): " + e1.getMessage()); } }
From source file:org.opentravel.schemacompiler.security.impl.JNDIAuthenticationProvider.java
/** * Uses the context provided to refresh the user information from the directory. * //from ww w . j av a 2 s . c om * @param userInfo the user information to be refreshed * @param context the directory context to use for the refresh */ private void refreshUserInfo(UserInfo userInfo, DirContext context) throws NamingException { String userId = (userInfo == null) ? null : userInfo.getUserId(); String userDn; if (userId != null) { System.out.println("REFRESHING USER: " + userId); if (mode == AuthenticationMode.USER_LOOKUP) { userDn = userPattern.format(new String[] { userId }); } else { userDn = findUserDn(userId, context); } if (userDn == null) { throw new NamingException("User account does not exist in the directory: " + userId); } else { // Make sure the account profile fields are populated from the directory String contextDnSuffix = "," + context.getNameInNamespace(); if (userDn.endsWith(contextDnSuffix)) { userDn = userDn.replaceAll(contextDnSuffix, ""); } Attributes userAttrs = context.getAttributes(userDn, new String[] { userLastNameAttribute, userFirstNameAttribute, userEmailAttribute }); userInfo.setLastName(getAttributeValue(userAttrs, userLastNameAttribute)); userInfo.setFirstName(getAttributeValue(userAttrs, userFirstNameAttribute)); userInfo.setEmailAddress(getAttributeValue(userAttrs, userEmailAttribute)); } } }
From source file:org.springframework.security.ldap.SpringSecurityLdapTemplate.java
/** * Internal method extracted to avoid code duplication in AD search. *///from ww w. j a v a2s . c om public static DirContextOperations searchForSingleEntryInternal(DirContext ctx, SearchControls searchControls, String base, String filter, Object[] params) throws NamingException { final DistinguishedName ctxBaseDn = new DistinguishedName(ctx.getNameInNamespace()); final DistinguishedName searchBaseDn = new DistinguishedName(base); final NamingEnumeration<SearchResult> resultsEnum = ctx.search(searchBaseDn, filter, params, buildControls(searchControls)); if (logger.isDebugEnabled()) { logger.debug("Searching for entry under DN '" + ctxBaseDn + "', base = '" + searchBaseDn + "', filter = '" + filter + "'"); } Set<DirContextOperations> results = new HashSet<>(); try { while (resultsEnum.hasMore()) { SearchResult searchResult = resultsEnum.next(); DirContextAdapter dca = (DirContextAdapter) searchResult.getObject(); Assert.notNull(dca, "No object returned by search, DirContext is not correctly configured"); if (logger.isDebugEnabled()) { logger.debug("Found DN: " + dca.getDn()); } results.add(dca); } } catch (PartialResultException e) { LdapUtils.closeEnumeration(resultsEnum); logger.info("Ignoring PartialResultException"); } if (results.size() == 0) { throw new IncorrectResultSizeDataAccessException(1, 0); } if (results.size() > 1) { throw new IncorrectResultSizeDataAccessException(1, results.size()); } return results.iterator().next(); }
From source file:org.wso2.carbon.identity.agent.onprem.userstore.manager.ldap.LDAPUserStoreManager.java
/** * @param searchFilter Username search filter. * @param returnedAtts Required attribute list of the user * @param dirContext LDAP connection context. * @return Search results for the given user. * @throws UserStoreException If an error occurs while searching. */// w ww.j a v a 2s. c om private NamingEnumeration<SearchResult> searchForUser(String searchFilter, String[] returnedAtts, DirContext dirContext) throws UserStoreException { SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); String searchBases = userStoreProperties.get(LDAPConstants.USER_SEARCH_BASE); if (returnedAtts[0].equals(CommonConstants.WILD_CARD_FILTER)) { returnedAtts = null; } searchCtls.setReturningAttributes(returnedAtts); if (log.isDebugEnabled()) { try { log.debug("Searching for user with SearchFilter: " + searchFilter + " in SearchBase: " + dirContext.getNameInNamespace()); } catch (NamingException e) { log.debug("Error while getting DN of search base", e); } if (returnedAtts == null) { log.debug("No attributes requested"); } else { for (String attribute : returnedAtts) { log.debug("Requesting attribute :" + attribute); } } } String[] searchBaseAraay = searchBases.split(CommonConstants.XML_PATTERN_SEPERATOR); NamingEnumeration<SearchResult> answer = null; try { for (String searchBase : searchBaseAraay) { answer = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchCtls); if (answer.hasMore()) { return answer; } } } catch (PartialResultException e) { // can be due to referrals in AD. so just ignore error String errorMessage = "Error occurred while search user for filter : " + searchFilter; if (isIgnorePartialResultException()) { if (log.isDebugEnabled()) { log.debug(errorMessage, e); } } else { throw new UserStoreException(errorMessage, e); } } catch (NamingException e) { String errorMessage = "Error occurred while search user for filter : " + searchFilter; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } return answer; }
From source file:org.wso2.carbon.identity.agent.onprem.userstore.manager.ldap.LDAPUserStoreManager.java
/** * @param userName Username of the user. * @param searchBase Searchbase which the user should be searched for. * @param searchFilter Search filter of the username. * @return DN of the user whose usename is given. * @throws UserStoreException If an error occurs while connecting to the LDAP userstore. */// ww w.ja v a 2s .com private String getNameInSpaceForUserName(String userName, String searchBase, String searchFilter) throws UserStoreException { boolean debug = log.isDebugEnabled(); String userDN = null; DirContext dirContext = this.connectionSource.getContext(); NamingEnumeration<SearchResult> answer = null; try { SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); if (log.isDebugEnabled()) { try { log.debug("Searching for user with SearchFilter: " + searchFilter + " in SearchBase: " + dirContext.getNameInNamespace()); } catch (NamingException e) { log.debug("Error while getting DN of search base", e); } } SearchResult userObj; String[] searchBases = searchBase.split(CommonConstants.XML_PATTERN_SEPERATOR); for (String base : searchBases) { answer = dirContext.search(escapeDNForSearch(base), searchFilter, searchCtls); if (answer.hasMore()) { userObj = answer.next(); if (userObj != null) { //no need to decode since , if decoded the whole string, can't be encoded again //eg CN=Hello\,Ok=test\,test, OU=Industry userDN = userObj.getNameInNamespace(); break; } } } if (debug) { log.debug("Name in space for " + userName + " is " + userDN); } } catch (Exception e) { log.debug(e.getMessage(), e); } finally { JNDIUtil.closeNamingEnumeration(answer); JNDIUtil.closeContext(dirContext); } return userDN; }
From source file:org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager.java
/** * */// w w w.java 2 s . co m public Map<String, String> getUserPropertyValues(String userName, String[] propertyNames, String profileName) throws UserStoreException { String userAttributeSeparator = ","; String userDN = null; LdapName ldn = (LdapName) userCache.get(userName); if (ldn == null) { // read list of patterns from user-mgt.xml String patterns = realmConfig.getUserStoreProperty(LDAPConstants.USER_DN_PATTERN); if (patterns != null && !patterns.isEmpty()) { if (log.isDebugEnabled()) { log.debug("Using User DN Patterns " + patterns); } if (patterns.contains("#")) { userDN = getNameInSpaceForUserName(userName); } else { userDN = MessageFormat.format(patterns, escapeSpecialCharactersForDN(userName)); } } } else { userDN = ldn.toString(); } Map<String, String> values = new HashMap<String, String>(); // if user name contains domain name, remove domain name String[] userNames = userName.split(CarbonConstants.DOMAIN_SEPARATOR); if (userNames.length > 1) { userName = userNames[1]; } DirContext dirContext = this.connectionSource.getContext(); String userSearchFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER); String searchFilter = userSearchFilter.replace("?", escapeSpecialCharactersForFilter(userName)); NamingEnumeration<?> answer = null; NamingEnumeration<?> attrs = null; try { if (userDN != null) { SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); if (propertyNames != null && propertyNames.length > 0) { searchCtls.setReturningAttributes(propertyNames); } if (log.isDebugEnabled()) { try { log.debug("Searching for user with SearchFilter: " + searchFilter + " in SearchBase: " + dirContext.getNameInNamespace()); } catch (NamingException e) { log.debug("Error while getting DN of search base", e); } if (propertyNames == null) { log.debug("No attributes requested"); } else { for (String attribute : propertyNames) { log.debug("Requesting attribute :" + attribute); } } } try { answer = dirContext.search(escapeDNForSearch(userDN), searchFilter, searchCtls); } catch (PartialResultException e) { // can be due to referrals in AD. so just ignore error String errorMessage = "Error occurred while searching directory context for user : " + userDN + " searchFilter : " + searchFilter; if (isIgnorePartialResultException()) { if (log.isDebugEnabled()) { log.debug(errorMessage, e); } } else { throw new UserStoreException(errorMessage, e); } } catch (NamingException e) { String errorMessage = "Error occurred while searching directory context for user : " + userDN + " searchFilter : " + searchFilter; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } } else { answer = this.searchForUser(searchFilter, propertyNames, dirContext); } while (answer.hasMoreElements()) { SearchResult sr = (SearchResult) answer.next(); Attributes attributes = sr.getAttributes(); if (attributes != null) { for (String name : propertyNames) { if (name != null) { Attribute attribute = attributes.get(name); if (attribute != null) { StringBuffer attrBuffer = new StringBuffer(); for (attrs = attribute.getAll(); attrs.hasMore();) { Object attObject = attrs.next(); String attr = null; if (attObject instanceof String) { attr = (String) attObject; } else if (attObject instanceof byte[]) { //if the attribute type is binary base64 encoded string will be returned attr = new String(Base64.encodeBase64((byte[]) attObject)); } if (attr != null && attr.trim().length() > 0) { String attrSeparator = realmConfig .getUserStoreProperty(MULTI_ATTRIBUTE_SEPARATOR); if (attrSeparator != null && !attrSeparator.trim().isEmpty()) { userAttributeSeparator = attrSeparator; } attrBuffer.append(attr + userAttributeSeparator); } String value = attrBuffer.toString(); /* * Length needs to be more than userAttributeSeparator.length() for a valid * attribute, since we * attach userAttributeSeparator */ if (value != null && value.trim().length() > userAttributeSeparator.length()) { value = value.substring(0, value.length() - userAttributeSeparator.length()); values.put(name, value); } } } } } } } } catch (NamingException e) { String errorMessage = "Error occurred while getting user property values for user : " + userName; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { // close the naming enumeration and free up resources JNDIUtil.closeNamingEnumeration(attrs); JNDIUtil.closeNamingEnumeration(answer); // close directory context JNDIUtil.closeContext(dirContext); } return values; }
From source file:org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager.java
/** * @param searchFilter/*from ww w.j a va 2 s . c om*/ * @param returnedAtts * @param dirContext * @return * @throws UserStoreException */ protected NamingEnumeration<SearchResult> searchForUser(String searchFilter, String[] returnedAtts, DirContext dirContext) throws UserStoreException { SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); String searchBases = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); if (returnedAtts != null && returnedAtts.length > 0) { searchCtls.setReturningAttributes(returnedAtts); } if (log.isDebugEnabled()) { try { log.debug("Searching for user with SearchFilter: " + searchFilter + " in SearchBase: " + dirContext.getNameInNamespace()); } catch (NamingException e) { log.debug("Error while getting DN of search base", e); } if (returnedAtts == null) { log.debug("No attributes requested"); } else { for (String attribute : returnedAtts) { log.debug("Requesting attribute :" + attribute); } } } String[] searchBaseAraay = searchBases.split("#"); NamingEnumeration<SearchResult> answer = null; try { for (String searchBase : searchBaseAraay) { answer = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchCtls); if (answer.hasMore()) { return answer; } } } catch (PartialResultException e) { // can be due to referrals in AD. so just ignore error String errorMessage = "Error occurred while search user for filter : " + searchFilter; if (isIgnorePartialResultException()) { if (log.isDebugEnabled()) { log.debug(errorMessage, e); } } else { throw new UserStoreException(errorMessage, e); } } catch (NamingException e) { String errorMessage = "Error occurred while search user for filter : " + searchFilter; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } return answer; }
From source file:org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager.java
/** * @param userName/* w w w . j av a2s . c o m*/ * @param searchBase * @param searchFilter * @return * @throws UserStoreException */ protected String getNameInSpaceForUserName(String userName, String searchBase, String searchFilter) throws UserStoreException { boolean debug = log.isDebugEnabled(); String userDN = null; DirContext dirContext = this.connectionSource.getContext(); NamingEnumeration<SearchResult> answer = null; try { SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); if (log.isDebugEnabled()) { try { log.debug("Searching for user with SearchFilter: " + searchFilter + " in SearchBase: " + dirContext.getNameInNamespace()); } catch (NamingException e) { log.debug("Error while getting DN of search base", e); } } SearchResult userObj = null; String[] searchBases = searchBase.split("#"); for (String base : searchBases) { answer = dirContext.search(escapeDNForSearch(base), searchFilter, searchCtls); if (answer.hasMore()) { userObj = (SearchResult) answer.next(); if (userObj != null) { //no need to decode since , if decoded the whole string, can't be encoded again //eg CN=Hello\,Ok=test\,test, OU=Industry userDN = userObj.getNameInNamespace(); break; } } } if (userDN != null) { LdapName ldn = new LdapName(userDN); userCache.put(userName, ldn); } if (debug) { log.debug("Name in space for " + userName + " is " + userDN); } } catch (Exception e) { log.debug(e.getMessage(), e); } finally { JNDIUtil.closeNamingEnumeration(answer); JNDIUtil.closeContext(dirContext); } return userDN; }