List of usage examples for javax.naming.directory Attributes get
Attribute get(String attrID);
From source file:dk.magenta.ldap.LDAPMultiBaseUserRegistry.java
private NodeDescription mapToNode(Map<String, String> attributeMapping, Map<String, String> attributeDefaults, SearchResult result) throws NamingException { NodeDescription nodeDescription = new NodeDescription(result.getNameInNamespace()); Attributes ldapAttributes = result.getAttributes(); // Parse the timestamp Attribute modifyTimestamp = ldapAttributes.get(this.modifyTimestampAttributeName); if (modifyTimestamp != null) { try {//from www . jav a2 s . c o m nodeDescription.setLastModified(this.timestampFormat.parse(modifyTimestamp.get().toString())); } catch (ParseException e) { throw new AlfrescoRuntimeException("Failed to parse timestamp.", e); } } // Apply the mapped attributes PropertyMap properties = nodeDescription.getProperties(); for (String key : attributeMapping.keySet()) { QName keyQName = QName.createQName(key, this.namespaceService); // cater for null String attributeName = attributeMapping.get(key); if (attributeName != null) { Attribute attribute = ldapAttributes.get(attributeName); if (attribute != null) { String value = (String) attribute.get(0); if (value != null) { properties.put(keyQName, value); } } else { String defaultValue = attributeDefaults.get(key); if (defaultValue != null) { properties.put(keyQName, defaultValue); } } } else { String defaultValue = attributeDefaults.get(key); if (defaultValue != null) { properties.put(keyQName, defaultValue); } } } return nodeDescription; }
From source file:org.jahia.services.usermanager.ldap.LDAPUserGroupProvider.java
/** * Map ldap attributes to jahia properties * * @param attributes/*from w ww . ja v a 2 s .c om*/ * @param isUser * @return */ private Properties attributesToJahiaProperties(Attributes attributes, boolean isUser) { Properties props = new Properties(); Map<String, String> attributesMapper = isUser ? userConfig.getAttributesMapper() : groupConfig.getAttributesMapper(); for (String propertyKey : attributesMapper.keySet()) { Attribute ldapAttribute = attributes.get(attributesMapper.get(propertyKey)); try { if (ldapAttribute != null && ldapAttribute.get() instanceof String) { props.put(propertyKey, ldapAttribute.get()); } } catch (NamingException e) { logger.error("Error reading LDAP attribute:" + ldapAttribute.toString()); } } return props; }
From source file:dk.magenta.ldap.LDAPMultiBaseUserRegistry.java
public String resolveDistinguishedName(String userId, AuthenticationDiagnostic diagnostic) throws AuthenticationException { if (logger.isDebugEnabled()) { logger.debug("resolveDistinguishedName userId:" + userId); }//from w w w. j a v a2 s. c o m SearchControls userSearchCtls = new SearchControls(); userSearchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); // Although we don't actually need any attributes, we ask for the UID for compatibility with Sun Directory Server. See ALF-3868 userSearchCtls.setReturningAttributes(new String[] { this.userIdAttributeName }); InitialDirContext ctx = null; for (String userSearchBase : this.userSearchBases) { String query = userSearchBase + "(&" + this.personQuery + "(" + this.userIdAttributeName + "= userId))"; NamingEnumeration<SearchResult> searchResults = null; SearchResult result = null; try { ctx = this.ldapInitialContextFactory.getDefaultIntialDirContext(diagnostic); // Execute the user query with an additional condition that ensures only the user with the required ID is // returned. Force RFC 2254 escaping of the user ID in the filter to avoid any manipulation searchResults = ctx.search(userSearchBase, "(&" + this.personQuery + "(" + this.userIdAttributeName + "={0}))", new Object[] { userId }, userSearchCtls); if (searchResults.hasMore()) { result = searchResults.next(); Attributes attributes = result.getAttributes(); Attribute uidAttribute = attributes.get(this.userIdAttributeName); if (uidAttribute == null) { if (this.errorOnMissingUID) { throw new AlfrescoRuntimeException( "User returned by user search does not have mandatory user id attribute " + attributes); } else { LDAPMultiBaseUserRegistry.logger .warn("User returned by user search does not have mandatory user id attribute " + attributes); } } // MNT:2597 We don't trust the LDAP server's treatment of whitespace, accented characters etc. We will // only resolve this user if the user ID matches else if (userId.equalsIgnoreCase((String) uidAttribute.get(0))) { String name = result.getNameInNamespace(); // Close the contexts, see ALF-20682 Context context = (Context) result.getObject(); if (context != null) { context.close(); } result = null; return name; } // Close the contexts, see ALF-20682 Context context = (Context) result.getObject(); if (context != null) { context.close(); } result = null; } } catch (NamingException e) { // Connection is good here - AuthenticationException would be thrown by ldapInitialContextFactory Object[] args1 = { userId, query }; diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_SEARCH, false, args1); } if (result != null) { try { Context context = (Context) result.getObject(); if (context != null) { context.close(); } } catch (Exception e) { logger.debug("error when closing result block context", e); } } if (searchResults != null) { try { searchResults.close(); } catch (Exception e) { logger.debug("error when closing searchResults context", e); } } } if (ctx != null) { try { ctx.close(); } catch (NamingException e) { logger.debug("error when closing ldap context", e); } } // failed to search // Object[] args = {e.getLocalizedMessage()}; throw new AuthenticationException("authentication.err.connection.ldap.search", diagnostic); }
From source file:edu.internet2.middleware.psp.ldap.LdapSpmlTarget.java
/** {@inheritDoc} */ public void execute(LookupRequest lookupRequest, LookupResponse lookupResponse) { Ldap ldap = null;//w ww . ja v a 2 s. c om try { // will not return AD Range option attrs // Attributes attributes = ldap.getAttributes(escapedDn, retAttrs); SearchFilter sf = new SearchFilter(); sf.setFilter("objectclass=*"); SearchControls sc = new SearchControls(); sc.setSearchScope(SearchControls.OBJECT_SCOPE); // This lookup requests attributes defined for *all* objects. // Perhaps there should be two searches, one for the identifier // and a second for attributes. String[] retAttrs = getPSP().getNames(getId(), lookupRequest.getReturnData()).toArray(new String[] {}); sc.setReturningAttributes(retAttrs); // TODO logging String dn = lookupRequest.getPsoID().getID(); String escapedDn = LdapSpmlTarget.escapeForwardSlash(dn); ldap = ldapPool.checkOut(); LOG.debug("Target '{}' - Searching '{}'", getId(), PSPUtil.toString(lookupRequest)); Iterator<SearchResult> searchResults = ldap.search(escapedDn, sf, sc); LOG.debug("Target '{}' - Searched '{}'", getId(), PSPUtil.toString(lookupRequest)); if (!searchResults.hasNext()) { fail(lookupResponse, ErrorCode.NO_SUCH_IDENTIFIER); return; } SearchResult result = searchResults.next(); if (searchResults.hasNext()) { fail(lookupResponse, ErrorCode.CUSTOM_ERROR, "More than one result found."); return; } Attributes attributes = result.getAttributes(); // return attributes in order defined by config OrderedLdapBeanFactory orderedLdapBeanFactory = new OrderedLdapBeanFactory(); // sort values SortedLdapBeanFactory sortedLdapBeanFactory = new SortedLdapBeanFactory(); LdapAttributes ldapAttributes = orderedLdapBeanFactory.newLdapAttributes(); for (String retAttr : retAttrs) { Attribute attr = attributes.get(retAttr); if (attr != null) { LdapAttribute ldapAttribute = sortedLdapBeanFactory.newLdapAttribute(); ldapAttribute.setAttribute(attr); ldapAttributes.addAttribute(ldapAttribute); } } LdapEntry entry = sortedLdapBeanFactory.newLdapEntry(); entry.setDn(dn); entry.setLdapAttributes(ldapAttributes); if (this.isLogLdif()) { LdapResult lr = sortedLdapBeanFactory.newLdapResult(); lr.addEntry(entry); LdifResultConverter lrc = new LdifResultConverter(); LOG.info("Target '{}' - LDIF\n{}", getId(), lrc.toLdif(lr)); } // build pso lookupResponse.setPso(getPSO(entry, lookupRequest.getReturnData())); } catch (NameNotFoundException e) { fail(lookupResponse, ErrorCode.NO_SUCH_IDENTIFIER); } catch (LdapPoolException e) { fail(lookupResponse, ErrorCode.CUSTOM_ERROR, e); } catch (InvalidNameException e) { fail(lookupResponse, ErrorCode.CUSTOM_ERROR, e); } catch (NamingException e) { fail(lookupResponse, ErrorCode.CUSTOM_ERROR, e); } catch (DSMLProfileException e) { fail(lookupResponse, ErrorCode.CUSTOM_ERROR, e); } catch (Spml2Exception e) { fail(lookupResponse, ErrorCode.CUSTOM_ERROR, e); } catch (PspException e) { fail(lookupResponse, ErrorCode.CUSTOM_ERROR, e); } finally { if (ldap != null) { ldapPool.checkIn(ldap); } } }
From source file:org.cggh.repo.security.sync.ldap.LDAPUserRegistry.java
protected NodeDescription mapToNode(Map<String, String> attributeMapping, Map<String, String> attributeDefaults, SearchResult result) throws NamingException { NodeDescription nodeDescription = new NodeDescription(result.getNameInNamespace()); Attributes ldapAttributes = result.getAttributes(); // Parse the timestamp Attribute modifyTimestamp = ldapAttributes.get(this.modifyTimestampAttributeName); if (modifyTimestamp != null) { try {//from w w w. ja va 2s . c o m nodeDescription.setLastModified(this.timestampFormat.parse(modifyTimestamp.get().toString())); } catch (ParseException e) { throw new AlfrescoRuntimeException("Failed to parse timestamp.", e); } } // Apply the mapped attributes PropertyMap properties = nodeDescription.getProperties(); for (String key : attributeMapping.keySet()) { QName keyQName = QName.createQName(key, this.namespaceService); // cater for null String attributeName = attributeMapping.get(key); if (attributeName != null) { Attribute attribute = ldapAttributes.get(attributeName); if (attribute != null) { String value = (String) attribute.get(0); if (value != null) { properties.put(keyQName, value); } } else { String defaultValue = attributeDefaults.get(key); if (defaultValue != null) { properties.put(keyQName, defaultValue); } } } else { String defaultValue = attributeDefaults.get(key); if (defaultValue != null) { properties.put(keyQName, defaultValue); } } } return nodeDescription; }
From source file:org.alfresco.repo.security.sync.ldap.LDAPUserRegistry.java
private NodeDescription mapToNode(Map<String, String> attributeMapping, Map<String, String> attributeDefaults, SearchResult result) throws NamingException { NodeDescription nodeDescription = new NodeDescription(result.getNameInNamespace()); Attributes ldapAttributes = result.getAttributes(); // Parse the timestamp Attribute modifyTimestamp = ldapAttributes.get(this.modifyTimestampAttributeName); if (modifyTimestamp != null) { try {/* w w w . j a va2 s. c o m*/ nodeDescription.setLastModified(this.timestampFormat.parse(modifyTimestamp.get().toString())); } catch (ParseException e) { throw new AlfrescoRuntimeException("Failed to parse timestamp.", e); } } // Apply the mapped attributes PropertyMap properties = nodeDescription.getProperties(); for (String key : attributeMapping.keySet()) { QName keyQName = QName.createQName(key, this.namespaceService); // cater for null String attributeName = attributeMapping.get(key); if (attributeName != null) { Attribute attribute = ldapAttributes.get(attributeName); String defaultAttribute = attributeDefaults.get(key); if (attribute != null) { String value = (String) attribute.get(0); if (value != null) { properties.put(keyQName, value); } } else if (defaultAttribute != null) { properties.put(keyQName, defaultAttribute); } else { // Make sure that a 2nd sync, updates deleted ldap attributes(MNT-14026) properties.put(keyQName, null); } } else { String defaultValue = attributeDefaults.get(key); if (defaultValue != null) { properties.put(keyQName, defaultValue); } } } return nodeDescription; }
From source file:org.alfresco.repo.security.sync.ldap.LDAPUserRegistry.java
public String resolveDistinguishedName(String userId, AuthenticationDiagnostic diagnostic) throws AuthenticationException { if (logger.isDebugEnabled()) { logger.debug("resolveDistinguishedName userId:" + userId); }/*from w w w.j av a 2 s . c o m*/ SearchControls userSearchCtls = new SearchControls(); userSearchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); // Although we don't actually need any attributes, we ask for the UID for compatibility with Sun Directory Server. See ALF-3868 userSearchCtls.setReturningAttributes(new String[] { this.userIdAttributeName }); String query = this.userSearchBase + "(&" + this.personQuery + "(" + this.userIdAttributeName + "= userId))"; NamingEnumeration<SearchResult> searchResults = null; SearchResult result = null; InitialDirContext ctx = null; try { ctx = this.ldapInitialContextFactory.getDefaultIntialDirContext(diagnostic); // Execute the user query with an additional condition that ensures only the user with the required ID is // returned. Force RFC 2254 escaping of the user ID in the filter to avoid any manipulation searchResults = ctx.search(this.userSearchBase, "(&" + this.personQuery + "(" + this.userIdAttributeName + "={0}))", new Object[] { userId }, userSearchCtls); if (searchResults.hasMore()) { result = searchResults.next(); Attributes attributes = result.getAttributes(); Attribute uidAttribute = attributes.get(this.userIdAttributeName); if (uidAttribute == null) { if (this.errorOnMissingUID) { throw new AlfrescoRuntimeException( "User returned by user search does not have mandatory user id attribute " + attributes); } else { LDAPUserRegistry.logger .warn("User returned by user search does not have mandatory user id attribute " + attributes); } } // MNT:2597 We don't trust the LDAP server's treatment of whitespace, accented characters etc. We will // only resolve this user if the user ID matches else if (userId.equalsIgnoreCase((String) uidAttribute.get(0))) { String name = result.getNameInNamespace(); // Close the contexts, see ALF-20682 Context context = (Context) result.getObject(); if (context != null) { context.close(); } result = null; return name; } // Close the contexts, see ALF-20682 Context context = (Context) result.getObject(); if (context != null) { context.close(); } result = null; } Object[] args = { userId, query }; diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_LOOKUP_USER, false, args); throw new AuthenticationException("authentication.err.connection.ldap.user.notfound", args, diagnostic); } catch (NamingException e) { // Connection is good here - AuthenticationException would be thrown by ldapInitialContextFactory Object[] args1 = { userId, query }; diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_SEARCH, false, args1); // failed to search Object[] args = { e.getLocalizedMessage() }; throw new AuthenticationException("authentication.err.connection.ldap.search", diagnostic, args, e); } finally { if (result != null) { try { Context context = (Context) result.getObject(); if (context != null) { context.close(); } } catch (Exception e) { logger.debug("error when closing result block context", e); } } if (searchResults != null) { try { searchResults.close(); } catch (Exception e) { logger.debug("error when closing searchResults context", e); } } if (ctx != null) { try { ctx.close(); } catch (NamingException e) { logger.debug("error when closing ldap context", e); } } } }
From source file:org.olat.ldap.manager.LDAPLoginManagerImpl.java
/** * Creates User in OLAT and ads user to LDAP securityGroup Required Attributes * have to be checked before this method. * // w w w. j a v a 2s .c o m * @param userAttributes Set of LDAP Attribute of User to be created */ @Override public Identity createAndPersistUser(Attributes userAttributes) { // Get and Check Config String[] reqAttrs = syncConfiguration.checkRequestAttributes(userAttributes); if (reqAttrs != null) { log.warn("Can not create and persist user, the following attributes are missing::" + ArrayUtils.toString(reqAttrs), null); return null; } String uid = getAttributeValue(userAttributes .get(syncConfiguration.getOlatPropertyToLdapAttribute(LDAPConstants.LDAP_USER_IDENTIFYER))); String email = getAttributeValue( userAttributes.get(syncConfiguration.getOlatPropertyToLdapAttribute(UserConstants.EMAIL))); // Lookup user if (securityManager.findIdentityByName(uid) != null) { log.error("Can't create user with username='" + uid + "', this username does already exist in OLAT database", null); return null; } if (!MailHelper.isValidEmailAddress(email)) { // needed to prevent possibly an AssertException in findIdentityByEmail breaking the sync! log.error("Cannot try to lookup user " + uid + " by email with an invalid email::" + email, null); return null; } if (userManager.userExist(email)) { log.error("Can't create user with email='" + email + "', a user with that email does already exist in OLAT database", null); return null; } // Create User (first and lastname is added in next step) User user = userManager.createUser(null, null, email); // Set User Property's (Iterates over Attributes and gets OLAT Property out // of olatexconfig.xml) NamingEnumeration<? extends Attribute> neAttr = userAttributes.getAll(); try { while (neAttr.hasMore()) { Attribute attr = neAttr.next(); String olatProperty = mapLdapAttributeToOlatProperty(attr.getID()); if (!attr.getID().equalsIgnoreCase( syncConfiguration.getOlatPropertyToLdapAttribute(LDAPConstants.LDAP_USER_IDENTIFYER))) { String ldapValue = getAttributeValue(attr); if (olatProperty == null || ldapValue == null) continue; user.setProperty(olatProperty, ldapValue); } } // Add static user properties from the configuration Map<String, String> staticProperties = syncConfiguration.getStaticUserProperties(); if (staticProperties != null && staticProperties.size() > 0) { for (Entry<String, String> staticProperty : staticProperties.entrySet()) { user.setProperty(staticProperty.getKey(), staticProperty.getValue()); } } } catch (NamingException e) { log.error("NamingException when trying to create and persist LDAP user with username::" + uid, e); return null; } catch (Exception e) { // catch any exception here to properly log error log.error("Unknown exception when trying to create and persist LDAP user with username::" + uid, e); return null; } // Create Identity Identity identity = securityManager.createAndPersistIdentityAndUser(uid, null, user, LDAPAuthenticationController.PROVIDER_LDAP, uid); // Add to SecurityGroup LDAP SecurityGroup secGroup = securityManager.findSecurityGroupByName(LDAPConstants.SECURITY_GROUP_LDAP); securityManager.addIdentityToSecurityGroup(identity, secGroup); // Add to SecurityGroup OLATUSERS secGroup = securityManager.findSecurityGroupByName(Constants.GROUP_OLATUSERS); securityManager.addIdentityToSecurityGroup(identity, secGroup); log.info("Created LDAP user username::" + uid); return identity; }
From source file:de.acosix.alfresco.mtsupport.repo.auth.ldap.EnhancedLDAPUserRegistry.java
protected Collection<String> lookupGroupChildren(final SearchResult searchResult, final String gid, final boolean disjoint, final LdapName groupDistinguishedNamePrefix, final LdapName userDistinguishedNamePrefix) throws NamingException { final InitialDirContext ctx = this.ldapInitialContextFactory.getDefaultIntialDirContext(); try {/*from w w w. jav a 2 s . com*/ LOGGER.debug("Processing group: {}, from source: {}", gid, searchResult.getNameInNamespace()); final Collection<String> children = new HashSet<>(); final Attributes attributes = searchResult.getAttributes(); Attribute memAttribute = this.getRangeRestrictedAttribute(attributes, this.memberAttributeName); int nextStart = this.attributeBatchSize; while (memAttribute != null) { for (int i = 0; i < memAttribute.size(); i++) { final String attribute = (String) memAttribute.get(i); if (attribute != null && attribute.length() > 0) { try { // Attempt to parse the member attribute as a DN. If this fails we have a fallback // in the catch block final LdapName distinguishedNameForComparison = fixedLdapName( attribute.toLowerCase(Locale.ENGLISH)); Attribute nameAttribute; // If the user and group search bases are different we may be able to recognize user // and group DNs without a secondary lookup if (disjoint) { final LdapName distinguishedName = fixedLdapName(attribute); final Attributes nameAttributes = distinguishedName .getRdn(distinguishedName.size() - 1).toAttributes(); // Recognize user DNs if (distinguishedNameForComparison.startsWith(userDistinguishedNamePrefix) && (nameAttribute = nameAttributes.get(this.userIdAttributeName)) != null) { final Collection<String> attributeValues = this.mapAttribute(nameAttribute, String.class); final String personName = attributeValues.iterator().next(); LOGGER.debug("User DN recognized: {}", personName); children.add(personName); continue; } // Recognize group DNs if (distinguishedNameForComparison.startsWith(groupDistinguishedNamePrefix) && (nameAttribute = nameAttributes .get(this.groupIdAttributeName)) != null) { final Collection<String> attributeValues = this.mapAttribute(nameAttribute, String.class); final String groupName = attributeValues.iterator().next(); LOGGER.debug("Group DN recognized: {}{}", AuthorityType.GROUP.getPrefixString(), groupName); children.add(AuthorityType.GROUP.getPrefixString() + groupName); continue; } } // If we can't determine the name and type from the DN alone, try a directory lookup if (distinguishedNameForComparison.startsWith(userDistinguishedNamePrefix) || distinguishedNameForComparison.startsWith(groupDistinguishedNamePrefix)) { try { final Attributes childAttributes = ctx.getAttributes(jndiName(attribute), new String[] { "objectclass", this.groupIdAttributeName, this.userIdAttributeName }); final Attribute objectClass = childAttributes.get("objectclass"); if (this.hasAttributeValue(objectClass, this.personType)) { nameAttribute = childAttributes.get(this.userIdAttributeName); if (nameAttribute == null) { if (this.errorOnMissingUID) { throw new AlfrescoRuntimeException( "User missing user id attribute DN =" + attribute + " att = " + this.userIdAttributeName); } else { LOGGER.warn("User missing user id attribute DN =" + attribute + " att = " + this.userIdAttributeName); continue; } } final Collection<String> attributeValues = this.mapAttribute(nameAttribute, String.class); final String personName = attributeValues.iterator().next(); LOGGER.debug("User DN recognized by directory lookup: {}", personName); children.add(personName); continue; } else if (this.hasAttributeValue(objectClass, this.groupType)) { nameAttribute = childAttributes.get(this.groupIdAttributeName); if (nameAttribute == null) { if (this.errorOnMissingGID) { final Object[] params = { searchResult.getNameInNamespace(), this.groupIdAttributeName }; throw new AlfrescoRuntimeException( "synchronization.err.ldap.get.group.id.missing", params); } else { LOGGER.warn("Missing GID on {}", childAttributes); continue; } } final Collection<String> attributeValues = this.mapAttribute(nameAttribute, String.class); final String groupName = attributeValues.iterator().next(); LOGGER.debug("Group DN recognized by directory lookup: {}{}", AuthorityType.GROUP.getPrefixString(), groupName); children.add(AuthorityType.GROUP.getPrefixString() + groupName); continue; } } catch (final NamingException e) { // Unresolvable name if (this.errorOnMissingMembers) { final Object[] params = { gid, attribute, e.getLocalizedMessage() }; throw new AlfrescoRuntimeException( "synchronization.err.ldap.group.member.missing.exception", params, e); } LOGGER.warn( "Failed to resolve member of group '{}, ' with distinguished name: {}", gid, attribute, e); continue; } } if (this.errorOnMissingMembers) { final Object[] params = { gid, attribute }; throw new AlfrescoRuntimeException("synchronization.err.ldap.group.member.missing", params); } LOGGER.warn("Failed to resolve member of group '{}' with distinguished name: {}", gid, attribute); } catch (final InvalidNameException e) { // The member attribute didn't parse as a DN. So assume we have a group class like // posixGroup (FDS) that directly lists user names LOGGER.debug("Member DN recognized as posixGroup: {}", attribute); children.add(attribute); } } } // If we are using attribute matching and we haven't got to the end (indicated by an asterisk), // fetch the next batch if (nextStart > 0 && !PATTERN_RANGE_END.matcher(memAttribute.getID().toLowerCase(Locale.ENGLISH)).find()) { final Attributes childAttributes = ctx.getAttributes( jndiName(searchResult.getNameInNamespace()), new String[] { this.memberAttributeName + ";range=" + nextStart + '-' + (nextStart + this.attributeBatchSize - 1) }); memAttribute = this.getRangeRestrictedAttribute(childAttributes, this.memberAttributeName); nextStart += this.attributeBatchSize; } else { memAttribute = null; } } return children; } finally { this.commonAfterQueryCleanup(null, null, ctx); } }