List of usage examples for javax.naming.directory Attribute get
Object get() throws NamingException;
From source file:com.alfaariss.oa.engine.user.provisioning.storage.external.jndi.JNDIExternalStorage.java
/** * Returns the values of the specified fields for the supplied id. * @see IExternalStorage#getFields(java.lang.String, java.util.List) *///w w w . jav a 2 s. co m public Hashtable<String, Object> getFields(String id, List<String> fields) throws UserException { Hashtable<String, Object> htReturn = new Hashtable<String, Object>(); DirContext oDirContext = null; NamingEnumeration oNamingEnumeration = null; try { try { oDirContext = new InitialDirContext(_htJNDIEnvironment); } catch (NamingException e) { _logger.error("Could not create the connection: " + _htJNDIEnvironment); throw new UserException(SystemErrors.ERROR_RESOURCE_CONNECT, e); } SearchControls oScope = new SearchControls(); oScope.setSearchScope(SearchControls.SUBTREE_SCOPE); String[] saFields = fields.toArray(new String[0]); oScope.setReturningAttributes(saFields); String searchFilter = resolveSearchQuery(id); try { oNamingEnumeration = oDirContext.search(_sDNBase, searchFilter, oScope); } catch (InvalidSearchFilterException e) { StringBuffer sbFailed = new StringBuffer("Wrong filter: "); sbFailed.append(searchFilter); sbFailed.append(" while searching for attributes '"); sbFailed.append(fields); sbFailed.append("' for id: "); sbFailed.append(id); _logger.error(sbFailed.toString(), e); throw new UserException(SystemErrors.ERROR_RESOURCE_RETRIEVE, e); } catch (NamingException e) { _logger.error("User unknown: " + id); throw new UserException(SystemErrors.ERROR_RESOURCE_RETRIEVE, e); } if (!oNamingEnumeration.hasMore()) { StringBuffer sbFailed = new StringBuffer("User with id '"); sbFailed.append(id); sbFailed.append("' not found after LDAP search with filter: "); sbFailed.append(searchFilter); _logger.error(sbFailed.toString()); throw new UserException(SystemErrors.ERROR_RESOURCE_RETRIEVE); } SearchResult oSearchResult = (SearchResult) oNamingEnumeration.next(); Attributes oAttributes = oSearchResult.getAttributes(); NamingEnumeration neAttributes = oAttributes.getAll(); while (neAttributes.hasMore()) { Attribute oAttribute = (Attribute) neAttributes.next(); String sAttributeName = oAttribute.getID(); if (oAttribute.size() > 1) { Vector<Object> vValue = new Vector<Object>(); NamingEnumeration neAttribute = oAttribute.getAll(); while (neAttribute.hasMore()) vValue.add(neAttribute.next()); htReturn.put(sAttributeName, vValue); } else { Object oValue = oAttribute.get(); if (oValue == null) oValue = ""; htReturn.put(sAttributeName, oValue); } } } catch (UserException e) { throw e; } catch (Exception e) { _logger.fatal("Could not retrieve fields: " + fields, e); throw new UserException(SystemErrors.ERROR_INTERNAL, e); } finally { if (oNamingEnumeration != null) { try { oNamingEnumeration.close(); } catch (Exception e) { _logger.error("Could not close Naming Enumeration after searching for user with id: " + id, e); } } if (oDirContext != null) { try { oDirContext.close(); } catch (NamingException e) { _logger.error("Could not close Dir Context after searching for user with id: " + id, e); } } } return htReturn; }
From source file:org.jenkinsci.plugins.reverse_proxy_auth.ReverseProxySecurityRealm.java
public LdapUserDetails updateLdapUserDetails(LdapUserDetails d) { LOGGER.log(Level.FINEST, "displayNameLdapAttribute" + displayNameLdapAttribute); LOGGER.log(Level.FINEST, "disableLdapEmailResolver" + disableLdapEmailResolver); LOGGER.log(Level.FINEST, "emailAddressLdapAttribute" + emailAddressLdapAttribute); if (d.getAttributes() == null) { LOGGER.log(Level.FINEST, "getAttributes is null"); } else {/*w ww . j a v a2 s. c o m*/ hudson.model.User u = hudson.model.User.get(d.getUsername()); if (!StringUtils.isBlank(displayNameLdapAttribute)) { LOGGER.log(Level.FINEST, "Getting user details from LDAP attributes"); try { Attribute attribute = d.getAttributes().get(displayNameLdapAttribute); String displayName = attribute == null ? null : (String) attribute.get(); LOGGER.log(Level.FINEST, "displayName is " + displayName); if (StringUtils.isNotBlank(displayName)) { u.setFullName(displayName); } } catch (NamingException e) { LOGGER.log(Level.FINEST, "Could not retrieve display name attribute", e); } } if (!disableLdapEmailResolver && !StringUtils.isBlank(emailAddressLdapAttribute)) { try { Attribute attribute = d.getAttributes().get(emailAddressLdapAttribute); String mailAddress = attribute == null ? null : (String) attribute.get(); if (StringUtils.isNotBlank(mailAddress)) { LOGGER.log(Level.FINEST, "mailAddress is " + mailAddress); UserProperty existing = u.getProperty(UserProperty.class); if (existing == null || !existing.hasExplicitlyConfiguredAddress()) { LOGGER.log(Level.FINEST, "user mail address has been changed"); u.addProperty(new Mailer.UserProperty(mailAddress)); } } } catch (NamingException e) { LOGGER.log(Level.FINEST, "Could not retrieve email address attribute", e); } catch (IOException e) { LOGGER.log(Level.WARNING, "Failed to associate the e-mail address", e); } } } return d; }
From source file:com.wfp.utils.LDAPUtils.java
public static String getUserImageAsString(String uid) { String base64String = null; if (uid != null && uid != "") { // Specify the attributes to return String searchFilter = "(&" + FILTER_LDAP_USERS + "((uid=" + uid + ")))"; String searchBase = LDAP_FILTER_URL + "uid=" + uid + "," + LDAP_BASE; String returnedAtts[] = { "" + PROPERTY_IMAGE }; // Specify the search scope SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchCtls.setReturningAttributes(returnedAtts); // Search for objects using the filter try {/*ww w . j a v a2 s. c o m*/ NamingEnumeration results = getSearchResults(getLDAPContext(), searchCtls, searchFilter, searchBase); while (results.hasMore()) { SearchResult searchResult = (SearchResult) results.next(); Attributes attributes = searchResult.getAttributes(); Attribute attr = attributes.get(PROPERTY_IMAGE); if (attr != null) base64String = new String( org.apache.commons.codec.binary.Base64.encodeBase64((byte[]) attr.get())); } } catch (NamingException e) { Logger.error(" Error occured while fetching user image 1334: getUserImageBytes(String uid):[" + e.getLocalizedMessage() + "]", LDAPUtils.class); } } return base64String; }
From source file:hudson.security.LDAPSecurityRealm.java
/** * Infer the root DN.//from w w w .j av a 2 s . co m * * @return null if not found. */ private String inferRootDN(String server) { try { Hashtable<String, String> props = new Hashtable<String, String>(); if (managerDN != null) { props.put(Context.SECURITY_PRINCIPAL, managerDN); props.put(Context.SECURITY_CREDENTIALS, getManagerPassword()); } props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); props.put(Context.PROVIDER_URL, getServerUrl() + '/'); DirContext ctx = new InitialDirContext(props); Attributes atts = ctx.getAttributes(""); Attribute a = atts.get("defaultNamingContext"); if (a != null) // this entry is available on Active Directory. See http://msdn2.microsoft.com/en-us/library/ms684291(VS.85).aspx return a.toString(); a = atts.get("namingcontexts"); if (a == null) { LOGGER.warning("namingcontexts attribute not found in root DSE of " + server); return null; } return a.get().toString(); } catch (NamingException e) { LOGGER.log(Level.WARNING, "Failed to connect to LDAP to infer Root DN for " + server, e); return null; } }
From source file:org.olat.ldap.LDAPLoginManagerImpl.java
/** * Extracts Value out of LDAP Attribute//from ww w. j a v a 2 s .c o m * * @param attribute LDAP Naming Attribute * @return String value of Attribute, null on Exception * @throws NamingException */ private String getAttributeValue(final Attribute attribute) { try { final String attrValue = (String) attribute.get(); return attrValue; } catch (final NamingException e) { logError("NamingException when trying to get attribute value for attribute::" + attribute, e); return null; } }
From source file:org.apache.zeppelin.realm.LdapRealm.java
private void addRoleIfMember(final String userDn, final SearchResult group, final Set<String> roleNames, final Set<String> groupNames, final LdapContextFactory ldapContextFactory) throws NamingException { NamingEnumeration<? extends Attribute> attributeEnum = null; NamingEnumeration<?> ne = null; try {//from w ww . ja va 2 s .c o m LdapName userLdapDn = new LdapName(userDn); Attribute attribute = group.getAttributes().get(getGroupIdAttribute()); String groupName = attribute.get().toString(); attributeEnum = group.getAttributes().getAll(); while (attributeEnum.hasMore()) { final Attribute attr = attributeEnum.next(); if (!memberAttribute.equalsIgnoreCase(attr.getID())) { continue; } ne = attr.getAll(); while (ne.hasMore()) { String attrValue = ne.next().toString(); if (memberAttribute.equalsIgnoreCase(MEMBER_URL)) { boolean dynamicGroupMember = isUserMemberOfDynamicGroup(userLdapDn, attrValue, ldapContextFactory); if (dynamicGroupMember) { groupNames.add(groupName); String roleName = roleNameFor(groupName); if (roleName != null) { roleNames.add(roleName); } else { roleNames.add(groupName); } } } else { // posix groups' members don' include the entire dn if (groupObjectClass.equalsIgnoreCase(POSIX_GROUP)) { attrValue = memberDn(attrValue); } if (userLdapDn.equals(new LdapName(attrValue))) { groupNames.add(groupName); String roleName = roleNameFor(groupName); if (roleName != null) { roleNames.add(roleName); } else { roleNames.add(groupName); } break; } } } } } finally { try { if (attributeEnum != null) { attributeEnum.close(); } } finally { if (ne != null) { ne.close(); } } } }
From source file:org.olat.ldap.LDAPLoginManagerImpl.java
/** * Creates list of all OLAT Users which have been deleted out of the LDAP directory but still exits in OLAT Configuration: Required Attributes = olatextconfig.xml * (property=reqAttrs) LDAP Base = olatextconfig.xml (property=ldapBase) * // w w w. j a v a 2s.c o m * @param syncTime The time to search in LDAP for changes since this time. SyncTime has to formatted: JJJJMMddHHmm * @param ctx The LDAP system connection, if NULL or closed NamingExecpiton is thrown * @return Returns list of Identity from the user which have been deleted in LDAP * @throws NamingException */ public List<Identity> getIdentitysDeletedInLdap(final LdapContext ctx) { if (ctx == null) { return null; } // Find all LDAP Users final String userID = LDAPLoginModule.mapOlatPropertyToLdapAttribute(LDAPConstants.LDAP_USER_IDENTIFYER); final String objctClass = LDAPLoginModule.getLdapUserObjectClass(); final List<String> ldapList = new ArrayList<String>(); searchInLdap(new LdapVisitor() { public void visit(final SearchResult result) throws NamingException { final Attributes attrs = result.getAttributes(); final NamingEnumeration<? extends Attribute> aEnum = attrs.getAll(); while (aEnum.hasMore()) { final Attribute attr = aEnum.next(); // use lowercase username ldapList.add(attr.get().toString().toLowerCase()); } } }, "(objectClass=" + objctClass + ")", new String[] { userID }, ctx); if (ldapList.isEmpty()) { logWarn("No users in LDAP found, can't create deletionList!!", null); return null; } // Find all User in OLAT, members of LDAPSecurityGroup final SecurityGroup ldapGroup = securityManager.findSecurityGroupByName(LDAPConstants.SECURITY_GROUP_LDAP); if (ldapGroup == null) { logError("Error getting users from OLAT security group '" + LDAPConstants.SECURITY_GROUP_LDAP + "' : group does not exist", null); return null; } final List<Identity> identityListToDelete = new ArrayList<Identity>(); final List<Identity> olatListIdentity = securityManager.getIdentitiesOfSecurityGroup(ldapGroup); for (final Identity ida : olatListIdentity) { // compare usernames with lowercase if (!ldapList.contains(ida.getName().toLowerCase())) { identityListToDelete.add(ida); } } return identityListToDelete; }
From source file:org.apache.zeppelin.realm.LdapRealm.java
protected Set<String> rolesFor(PrincipalCollection principals, String userNameIn, final LdapContext ldapCtx, final LdapContextFactory ldapContextFactory, Session session) throws NamingException { final Set<String> roleNames = new HashSet<>(); final Set<String> groupNames = new HashSet<>(); final String userName; if (getUserLowerCase()) { log.debug("userLowerCase true"); userName = userNameIn.toLowerCase(); } else {//ww w . j av a 2 s . c om userName = userNameIn; } String userDn = getUserDnForSearch(userName); // Activate paged results int pageSize = getPagingSize(); if (log.isDebugEnabled()) { log.debug("Ldap PagingSize: " + pageSize); } int numResults = 0; byte[] cookie = null; try { ldapCtx.addToEnvironment(Context.REFERRAL, "ignore"); ldapCtx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) }); do { // ldapsearch -h localhost -p 33389 -D // uid=guest,ou=people,dc=hadoop,dc=apache,dc=org -w guest-password // -b dc=hadoop,dc=apache,dc=org -s sub '(objectclass=*)' NamingEnumeration<SearchResult> searchResultEnum = null; SearchControls searchControls = getGroupSearchControls(); try { if (groupSearchEnableMatchingRuleInChain) { searchResultEnum = ldapCtx.search(getGroupSearchBase(), String .format(MATCHING_RULE_IN_CHAIN_FORMAT, groupObjectClass, memberAttribute, userDn), searchControls); while (searchResultEnum != null && searchResultEnum.hasMore()) { // searchResults contains all the groups in search scope numResults++; final SearchResult group = searchResultEnum.next(); Attribute attribute = group.getAttributes().get(getGroupIdAttribute()); String groupName = attribute.get().toString(); String roleName = roleNameFor(groupName); if (roleName != null) { roleNames.add(roleName); } else { roleNames.add(groupName); } } } else { // Default group search filter String searchFilter = String.format("(objectclass=%1$s)", groupObjectClass); // If group search filter is defined in Shiro config, then use it if (groupSearchFilter != null) { searchFilter = expandTemplate(groupSearchFilter, userName); //searchFilter = String.format("%1$s", groupSearchFilter); } if (log.isDebugEnabled()) { log.debug("Group SearchBase|SearchFilter|GroupSearchScope: " + getGroupSearchBase() + "|" + searchFilter + "|" + groupSearchScope); } searchResultEnum = ldapCtx.search(getGroupSearchBase(), searchFilter, searchControls); while (searchResultEnum != null && searchResultEnum.hasMore()) { // searchResults contains all the groups in search scope numResults++; final SearchResult group = searchResultEnum.next(); addRoleIfMember(userDn, group, roleNames, groupNames, ldapContextFactory); } } } catch (PartialResultException e) { log.debug("Ignoring PartitalResultException"); } finally { if (searchResultEnum != null) { searchResultEnum.close(); } } // Re-activate paged results ldapCtx.setRequestControls( new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) }); } while (cookie != null); } catch (SizeLimitExceededException e) { log.info("Only retrieved first " + numResults + " groups due to SizeLimitExceededException."); } catch (IOException e) { log.error("Unabled to setup paged results"); } // save role names and group names in session so that they can be // easily looked up outside of this object session.setAttribute(SUBJECT_USER_ROLES, roleNames); session.setAttribute(SUBJECT_USER_GROUPS, groupNames); if (!groupNames.isEmpty() && (principals instanceof MutablePrincipalCollection)) { ((MutablePrincipalCollection) principals).addAll(groupNames, getName()); } if (log.isDebugEnabled()) { log.debug("User RoleNames: " + userName + "::" + roleNames); } return roleNames; }
From source file:org.craftercms.studio.impl.v1.service.security.DbWithLdapExtensionSecurityProvider.java
@Override public String authenticate(String username, String password) throws BadCredentialsException, AuthenticationSystemException { // Mapper for user data if user is successfully authenticated AuthenticatedLdapEntryContextMapper<User> mapper = new AuthenticatedLdapEntryContextMapper<User>() { @Override// www . jav a 2 s . c o m public User mapWithContext(DirContext dirContext, LdapEntryIdentification ldapEntryIdentification) { try { // User entry - extract attributes DirContextOperations dirContextOperations = (DirContextOperations) dirContext .lookup(ldapEntryIdentification.getRelativeName()); Attributes attributes = dirContextOperations.getAttributes(); String emailAttribName = studioConfiguration.getProperty(SECURITY_LDAP_USER_ATTRIBUTE_EMAIL); String firstNameAttribName = studioConfiguration .getProperty(SECURITY_LDAP_USER_ATTRIBUTE_FIRST_NAME); String lastNameAttribName = studioConfiguration .getProperty(SECURITY_LDAP_USER_ATTRIBUTE_LAST_NAME); String siteIdAttribName = studioConfiguration.getProperty(SECURITY_LDAP_USER_ATTRIBUTE_SITE_ID); String groupNameAttribName = studioConfiguration .getProperty(SECURITY_LDAP_USER_ATTRIBUTE_GROUP_NAME); Attribute emailAttrib = attributes.get(emailAttribName); Attribute firstNameAttrib = attributes.get(firstNameAttribName); Attribute lastNameAttrib = attributes.get(lastNameAttribName); Attribute siteIdAttrib = attributes.get(siteIdAttribName); Attribute groupNameAttrib = attributes.get(groupNameAttribName); User user = new User(); user.setGroups(new ArrayList<>()); user.setActive(1); user.setUsername(username); if (emailAttrib != null && emailAttrib.get() != null) { user.setEmail(emailAttrib.get().toString()); } else { logger.error("No LDAP attribute " + emailAttribName + " found for username " + username + ". User will not be imported into DB."); return null; } if (firstNameAttrib != null && firstNameAttrib.get() != null) { user.setFirstname(firstNameAttrib.get().toString()); } else { logger.warn("No LDAP attribute " + firstNameAttribName + " found for username " + username); } if (lastNameAttrib != null && lastNameAttrib.get() != null) { user.setLastname(lastNameAttrib.get().toString()); } else { logger.warn("No LDAP attribute " + lastNameAttribName + " found for username " + username); } if (siteIdAttrib != null && siteIdAttrib.get() != null) { Map<String, Object> params = new HashMap<>(); NamingEnumeration siteIdValues = siteIdAttrib.getAll(); while (siteIdValues.hasMore()) { Object siteIdObj = siteIdValues.next(); if (siteIdObj != null) { String[] siteIdAndGroupName = extractSiteIdAndGroupNameFromAttributeValue( siteIdObj.toString()); if (siteIdAndGroupName.length > 0) { params.put("siteId", siteIdAndGroupName[0]); SiteFeed siteFeed = siteFeedMapper.getSite(params); if (siteFeed != null) { // Add groups, first the one that's specific to the site if (siteIdAndGroupName.length > 1) { addGroupToUser(user, siteIdAndGroupName[1], siteFeed); } extractGroupsFromAttribute(user, groupNameAttribName, groupNameAttrib, siteFeed); } else { logger.warn("Not site found for ID " + siteIdAndGroupName[0]); } } } } } else { String defaultSiteId = studioConfiguration.getProperty(SECURITY_LDAP_DEFAULT_SITE_ID); logger.debug("Assigning user " + username + " to default site " + defaultSiteId); Map<String, Object> params = new HashMap<>(); params.put("siteId", defaultSiteId); SiteFeed siteFeed = siteFeedMapper.getSite(params); if (siteFeed != null) { extractGroupsFromAttribute(user, groupNameAttribName, groupNameAttrib, siteFeed); } else { logger.warn("No site found for default site ID " + defaultSiteId); } } return user; } catch (NamingException e) { logger.error("Error getting details from LDAP for username " + username, e); return null; } } }; // Create ldap query to authenticate user LdapQuery ldapQuery = query().where(studioConfiguration.getProperty(SECURITY_LDAP_USER_ATTRIBUTE_USERNAME)) .is(username); User user; try { user = ldapTemplate.authenticate(ldapQuery, password, mapper); } catch (EmptyResultDataAccessException e) { logger.info("User " + username + " not found with external security provider. Trying to authenticate against studio database"); // When user not found try to authenticate against studio database return super.authenticate(username, password); } catch (CommunicationException e) { logger.info("Failed to connect with external security provider. " + "Trying to authenticate against studio database"); // When user not found try to authenticate against studio database return super.authenticate(username, password); } catch (AuthenticationException e) { logger.error("Authentication failed with the LDAP system", e); throw new BadCredentialsException(); } catch (Exception e) { logger.error("Authentication failed with the LDAP system", e); throw new AuthenticationSystemException("Authentication failed with the LDAP system", e); } if (user != null) { // When user authenticated against LDAP, upsert user data into studio database if (super.userExists(username)) { try { boolean success = updateUserInternal(user.getUsername(), user.getFirstname(), user.getLastname(), user.getEmail()); if (success) { ActivityService.ActivityType activityType = ActivityService.ActivityType.UPDATED; Map<String, String> extraInfo = new HashMap<>(); extraInfo.put(DmConstants.KEY_CONTENT_TYPE, StudioConstants.CONTENT_TYPE_USER); activityService.postActivity(getSystemSite(), user.getUsername(), user.getUsername(), activityType, ActivityService.ActivitySource.API, extraInfo); } } catch (UserNotFoundException e) { logger.error( "Error updating user " + username + " with data from external authentication provider", e); throw new AuthenticationSystemException( "Error updating user " + username + " with data from external authentication provider", e); } } else { try { boolean success = createUser(user.getUsername(), password, user.getFirstname(), user.getLastname(), user.getEmail(), true); if (success) { ActivityService.ActivityType activityType = ActivityService.ActivityType.CREATED; Map<String, String> extraInfo = new HashMap<>(); extraInfo.put(DmConstants.KEY_CONTENT_TYPE, StudioConstants.CONTENT_TYPE_USER); activityService.postActivity(getSystemSite(), user.getUsername(), user.getUsername(), activityType, ActivityService.ActivitySource.API, extraInfo); } } catch (UserAlreadyExistsException e) { logger.error("Error adding user " + username + " from external authentication provider", e); throw new AuthenticationSystemException( "Error adding user " + username + " from external authentication provider", e); } } for (Group group : user.getGroups()) { try { upsertUserGroup(group.getSite(), group.getName(), user.getUsername()); } catch (GroupAlreadyExistsException | SiteNotFoundException | UserNotFoundException | UserAlreadyExistsException | GroupNotFoundException e) { logger.error("Failed to upsert user groups data from LDAP", e); } } String token = createToken(user); storeSessionTicket(token); storeSessionUsername(username); return token; } else { logger.error("Failed to retrieve LDAP user details"); throw new AuthenticationSystemException("Failed to retrieve LDAP user details"); } }
From source file:com.dtolabs.rundeck.jetty.jaas.JettyCachingLdapLoginModule.java
private String safeGetAttributeAsString(final Attribute attribute) { try {/* ww w . j av a 2s . c o m*/ if (attribute == null || attribute.get() == null) return null; return attribute.get().toString(); } catch (NamingException nex) { LOG.warn("Unable to retrieve rundeck sync attributes. User will not be synced.", nex); } return null; }