org.springframework.ldap.filter.EqualsFilter Java Examples

The following examples show how to use org.springframework.ldap.filter.EqualsFilter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LdapServiceImpl.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
@Override
public User getUser(String realm, String uid) {
    AndFilter filter = new AndFilter();
    filter.and(new EqualsFilter(OBJECTCLASS, userObjectClass)).and(new EqualsFilter(userSearchAttribute, uid));
    DistinguishedName dn = new DistinguishedName("ou=" + realm);
    User user;
    try {
        List userList = ldapTemplate.search(dn, filter.toString(), SearchControls.SUBTREE_SCOPE, new String[] {
                "*", CREATE_TIMESTAMP, MODIFY_TIMESTAMP }, new UserContextMapper());
        if (userList == null || userList.size() == 0) {
            throw new EmptyResultDataAccessException(1);
        } else if (userList.size() > 1) {
            throw new IncorrectResultSizeDataAccessException("User must be unique", 1);
        }
        user = (User) userList.get(0);
        user.setUid(uid);
        user.setGroups(getGroupNames(getUserGroups(realm, uid)));
    } catch (EmptyResultDataAccessException e) {
        return null;
    }
    return user;
}
 
Example #2
Source File: LdapTemplateTest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@Test
public void verifyThatFindOneThrowsIncorrectResultSizeDataAccessExceptionWhenMoreResults() throws Exception {
    Class<Object> expectedClass = Object.class;

    when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock);
    when(odmMock.filterFor(expectedClass,
            new EqualsFilter("ou", "somevalue"))).thenReturn(new EqualsFilter("ou", "somevalue"));

    DirContextAdapter expectedObject = new DirContextAdapter();
    SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes());

    setupSearchResults(searchControlsRecursive(), new SearchResult[]{searchResult, searchResult});

    Object expectedResult = expectedObject;
    when(odmMock.mapFromLdapDataEntry(expectedObject, expectedClass)).thenReturn(expectedResult, expectedResult);

    try {
        tested.findOne(query().where("ou").is("somevalue"), expectedClass);
        fail("EmptyResultDataAccessException expected");
    } catch (IncorrectResultSizeDataAccessException expected) {
        assertThat(true).isTrue();
    }

    verify(namingEnumerationMock).close();
    verify(dirContextMock).close();
}
 
Example #3
Source File: LdapTemplateTest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@Test
public void verifyThatFindOneThrowsEmptyResultIfNoResult() throws Exception {
    Class<Object> expectedClass = Object.class;

    when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock);
    when(odmMock.filterFor(expectedClass,
            new EqualsFilter("ou", "somevalue"))).thenReturn(new EqualsFilter("ou", "somevalue"));

    noSearchResults(searchControlsRecursive());

    try {
        tested.findOne(query().where("ou").is("somevalue"), expectedClass);
        fail("EmptyResultDataAccessException expected");
    } catch (EmptyResultDataAccessException expected) {
        assertThat(true).isTrue();
    }

    verify(namingEnumerationMock).close();
    verify(dirContextMock).close();
    verify(odmMock, never()).mapFromLdapDataEntry(any(LdapDataEntry.class), any(Class.class));
}
 
Example #4
Source File: LdapTemplateTest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@Test
public void testFindOne() throws Exception {
    Class<Object> expectedClass = Object.class;

    when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock);
    when(odmMock.filterFor(expectedClass,
            new EqualsFilter("ou", "somevalue"))).thenReturn(new EqualsFilter("ou", "somevalue"));

    DirContextAdapter expectedObject = new DirContextAdapter();
    SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes());
    singleSearchResult(searchControlsRecursive(), searchResult);

    Object expectedResult = expectedObject;
    when(odmMock.mapFromLdapDataEntry(expectedObject, expectedClass)).thenReturn(expectedResult);

    Object result = tested.findOne(query()
            .where("ou").is("somevalue"), expectedClass);

    verify(namingEnumerationMock).close();
    verify(dirContextMock).close();

    assertThat(result).isSameAs(expectedResult);
}
 
Example #5
Source File: LdapContextSourceIntegrationTest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
   @Category(NoAdTest.class)
public void verifyAuthenticate() {
	EqualsFilter filter = new EqualsFilter("cn", "Some Person2");
	List<String> results = ldapTemplate.search("", filter.toString(), new DnContextMapper());
	if (results.size() != 1) {
		throw new IncorrectResultSizeDataAccessException(1, results.size());
	}

	DirContext ctx = null;
	try {
		ctx = tested.getContext(results.get(0), "password");
		assertThat(true).isTrue();
	}
	catch (Exception e) {
		fail("Authentication failed");
	}
	finally {
		LdapUtils.closeContext(ctx);
	}
}
 
Example #6
Source File: LdapTemplateAuthenticationITest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@Test
   @Category(NoAdTest.class)
public void testAuthenticateWithLookupOperationPerformedOnAuthenticatedContext() {
	AndFilter filter = new AndFilter();
	filter.and(new EqualsFilter("objectclass", "person")).and(new EqualsFilter("uid", "some.person3"));
	AuthenticatedLdapEntryContextCallback contextCallback = new AuthenticatedLdapEntryContextCallback() {
		public void executeWithContext(DirContext ctx, LdapEntryIdentification ldapEntryIdentification) {
			try {
				DirContextAdapter adapter = (DirContextAdapter) ctx.lookup(ldapEntryIdentification.getRelativeDn());
				assertThat(adapter.getStringAttribute("cn")).isEqualTo("Some Person3");
			}
			catch (NamingException e) {
				throw new RuntimeException("Failed to lookup " + ldapEntryIdentification.getRelativeDn(), e);
			}
		}
	};
	assertThat(tested.authenticate("", filter.toString(), "password", contextCallback)).isTrue();
}
 
Example #7
Source File: UserService.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
/**
 *
 * @param realm
 *            The realm under which the user exists
 * @param userId
 *            The id of the user
 * @return List of roles assigned to this user
 */
public List<String> getUserGroups(String realm, String userId) {
    DistinguishedName dn = new DistinguishedName("ou=" + realm);
    AndFilter filter = new AndFilter();
    filter.and(new EqualsFilter("objectclass", groupObjectClass)).and(
            new EqualsFilter(groupSearchAttribute, userId));
    @SuppressWarnings("unchecked")
    List<String> groups = ldapTemplate.search(dn, filter.toString(), new GroupContextMapper());

    // map the roles in LDAP which are better suited for Posix systems to
    // the roles used by the API
    List<String> result = new LinkedList<String>();
    for (String group : groups) {
        result.add(LDAP_ROLE_MAPPING.containsKey(group) ? LDAP_ROLE_MAPPING.get(group) : group);
    }
    return result;
}
 
Example #8
Source File: LdapUtils.java    From cxf with Apache License 2.0 6 votes vote down vote up
public static Name getDnOfEntry(LdapTemplate ldapTemplate, String baseDN,
    String objectClass, String filterAttributeName, String filterAttributeValue) {

    ContextMapper<Name> mapper =
        new AbstractContextMapper<Name>() {
            public Name doMapFromContext(DirContextOperations ctx) {
                return ctx.getDn();
            }
        };

    AndFilter filter = new AndFilter();
    filter.and(
        new EqualsFilter("objectclass", objectClass)).and(
            new EqualsFilter(filterAttributeName, filterAttributeValue));

    List<Name> result = ldapTemplate.search((baseDN == null) ? "" : baseDN, filter.toString(),
        SearchControls.SUBTREE_SCOPE, mapper);

    if (result != null && !result.isEmpty()) {
        //not only the first one....
        return result.get(0);
    }
    return null;
}
 
Example #9
Source File: LdapCredentialsAuthenticator.java    From ob1k with Apache License 2.0 6 votes vote down vote up
@Override
public ComposableFuture<Boolean> authenticate(final Credentials<UserPasswordToken> credentials) {
  final String username = credentials.get().getUsername();
  final LdapQuery query = LdapQueryBuilder.query().filter(new EqualsFilter(UID_ATTRIBUTE, username));
  return ComposableFutures.submit(new Callable<Boolean>() {
    @Override
    public Boolean call() throws Exception {
      try {
        ldapTemplate.authenticate(query, new String(credentials.get().getPassword()));
        return true;
      } catch (final Exception e) {
        return false;
      }
    }
  });
}
 
Example #10
Source File: LdapClient.java    From taskana with Apache License 2.0 6 votes vote down vote up
public List<AccessIdRepresentationModel> searchGroupsofUsersIsMember(final String name)
    throws InvalidArgumentException {
  LOGGER.debug("entry to searchGroupsofUsersIsMember(name = {}).", name);
  isInitOrFail();
  testMinSearchForLength(name);

  final AndFilter andFilter = new AndFilter();
  andFilter.and(new WhitespaceWildcardsFilter(getGroupNameAttribute(), ""));
  andFilter.and(new EqualsFilter(getGroupsOfUser(), name));

  String[] userAttributesToReturn = {getUserIdAttribute(), getGroupNameAttribute()};

  final List<AccessIdRepresentationModel> accessIds =
      ldapTemplate.search(
          getGroupSearchBase(),
          andFilter.encode(),
          SearchControls.SUBTREE_SCOPE,
          userAttributesToReturn,
          new GroupContextMapper());
  LOGGER.debug(
      "exit from searchGroupsofUsersIsMember. Retrieved the following users: {}.", accessIds);
  return accessIds;
}
 
Example #11
Source File: LdapClient.java    From taskana with Apache License 2.0 6 votes vote down vote up
public List<AccessIdRepresentationModel> searchGroupsByName(final String name)
    throws InvalidArgumentException {
  LOGGER.debug("entry to searchGroupsByName(name = {}).", name);
  isInitOrFail();
  testMinSearchForLength(name);

  final AndFilter andFilter = new AndFilter();
  andFilter.and(new EqualsFilter(getGroupSearchFilterName(), getGroupSearchFilterValue()));
  final OrFilter orFilter = new OrFilter();
  orFilter.or(new WhitespaceWildcardsFilter(getGroupNameAttribute(), name));
  if (!CN.equals(getGroupNameAttribute())) {
    orFilter.or(new WhitespaceWildcardsFilter(CN, name));
  }
  andFilter.and(orFilter);

  final List<AccessIdRepresentationModel> accessIds =
      ldapTemplate.search(
          getGroupSearchBase(),
          andFilter.encode(),
          SearchControls.SUBTREE_SCOPE,
          getLookUpGroupAttributesToReturn(),
          new GroupContextMapper());
  LOGGER.debug("Exit from searchGroupsByName. Retrieved the following groups: {}", accessIds);
  return accessIds;
}
 
Example #12
Source File: LdapTemplateAuthenticationITest.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
@Test
@Category(NoAdTest.class)
public void testAuthenticateWithLdapQuery() {
    AndFilter filter = new AndFilter();
    filter.and(new EqualsFilter("objectclass", "person")).and(new EqualsFilter("uid", "some.person3"));
    tested.authenticate(query()
            .where("objectclass").is("person")
            .and("uid").is("some.person3"),
            "password");
}
 
Example #13
Source File: ChoerodonAuthenticationProvider.java    From oauth-server with Apache License 2.0 5 votes vote down vote up
private AndFilter getLoginFilter(LdapE ldap, String loginName) {
    String objectClass = ldap.getObjectClass();
    String[] arr = objectClass.split(",");
    AndFilter andFilter = new AndFilter();
    for (String str : arr) {
        andFilter.and(new EqualsFilter(OBJECT_CLASS, str));
    }
    andFilter.and(new EqualsFilter(ldap.getLoginNameField(), loginName));
    return andFilter;
}
 
Example #14
Source File: LdapAuthRepositoryCustomImpl.java    From Spring-5.0-Projects with MIT License 5 votes vote down vote up
/**
 * This method will return roles of given user.
 */
@Override
public List<LdapGranntedAuthority> getUserAuthorities(String userName) {
	AndFilter groupFilter = new AndFilter();
	groupFilter.and(new EqualsFilter("objectclass","groupOfNames"));
	groupFilter.and(new EqualsFilter("member","uid="+userName+",ou=users,o=packtPublisher"));
	List<LdapGranntedAuthority> userRoleLst = ldapTemplate.search(LdapQueryBuilder.query().filter(groupFilter),new LdapRoleMapper());
	return userRoleLst;
}
 
Example #15
Source File: LdapClient.java    From taskana with Apache License 2.0 5 votes vote down vote up
public List<AccessIdRepresentationModel> searchUsersByNameOrAccessId(final String name)
    throws InvalidArgumentException {
  LOGGER.debug("entry to searchUsersByNameOrAccessId(name = {}).", name);
  isInitOrFail();
  testMinSearchForLength(name);

  final AndFilter andFilter = new AndFilter();
  andFilter.and(new EqualsFilter(getUserSearchFilterName(), getUserSearchFilterValue()));
  final OrFilter orFilter = new OrFilter();

  orFilter.or(new WhitespaceWildcardsFilter(getUserFirstnameAttribute(), name));
  orFilter.or(new WhitespaceWildcardsFilter(getUserLastnameAttribute(), name));
  orFilter.or(new WhitespaceWildcardsFilter(getUserIdAttribute(), name));
  andFilter.and(orFilter);

  String[] userAttributesToReturn = {
    getUserFirstnameAttribute(), getUserLastnameAttribute(), getUserIdAttribute()
  };

  final List<AccessIdRepresentationModel> accessIds =
      ldapTemplate.search(
          getUserSearchBase(),
          andFilter.encode(),
          SearchControls.SUBTREE_SCOPE,
          userAttributesToReturn,
          new UserContextMapper());
  LOGGER.debug(
      "exit from searchUsersByNameOrAccessId. Retrieved the following users: {}.", accessIds);
  return accessIds;
}
 
Example #16
Source File: DefaultObjectDirectoryMapper.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
/**
 * Adds an {@link org.springframework.ldap.odm.annotations} annotated class to the set
 * managed by this OdmManager.
 *
 * @param managedClass The class to add to the managed set.
 */
private EntityData addManagedClass(Class<?> managedClass) {
    if (LOG.isDebugEnabled()) {
        LOG.debug(String.format("Adding class %1$s to managed set", managedClass));
    }

    // Extract the meta-data from the class
    ObjectMetaData metaData=new ObjectMetaData(managedClass);

    // Check we can construct the target type - it must have a zero argument public constructor
    try {
        managedClass.getConstructor();
    } catch (NoSuchMethodException e) {
        throw new InvalidEntryException(String.format(
                "The class %1$s must have a zero argument constructor to be an Entry", managedClass), e);
    }

    // Check we have all of the necessary converters for the class
    for (Field field : metaData) {
        AttributeMetaData attributeInfo = metaData.getAttribute(field);
        if (!attributeInfo.isTransient() && !attributeInfo.isId() && !(attributeInfo.isObjectClass())) {
            verifyConversion(managedClass, field, attributeInfo);
        }
    }

    // Filter so we only read the object classes supported by the managedClass
    AndFilter ocFilter = new AndFilter();
    for (CaseIgnoreString oc : metaData.getObjectClasses()) {
        ocFilter.and(new EqualsFilter(OBJECT_CLASS_ATTRIBUTE, oc.toString()));
    }

    EntityData newValue = new EntityData(metaData, ocFilter);
    EntityData previousValue = metaDataMap.putIfAbsent(managedClass, newValue);
    // Just in case someone beat us to it
    if(previousValue != null) {
        return previousValue;
    }

    return newValue;
}
 
Example #17
Source File: SimpleLdapTemplateITest.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
@Test
   @Category(NoAdTest.class)
public void testAuthenticate() {
	AndFilter filter = new AndFilter();
	filter.and(new EqualsFilter("objectclass", "person")).and(new EqualsFilter("uid", "some.person3"));
	assertThat(ldapTemplate.authenticate("", filter.toString(), "password")).isTrue();
}
 
Example #18
Source File: LdapClient.java    From taskana with Apache License 2.0 5 votes vote down vote up
public List<AccessIdRepresentationModel> getUsersByAccessId(final String accessId) {
  LOGGER.debug("entry to searchUsersByAccessId(name = {}).", accessId);
  isInitOrFail();

  final AndFilter andFilter = new AndFilter();
  andFilter.and(new EqualsFilter(getUserSearchFilterName(), getUserSearchFilterValue()));
  andFilter.and(new EqualsFilter(getUserIdAttribute(), accessId));

  String[] userAttributesToReturn = {
    getUserFirstnameAttribute(), getUserLastnameAttribute(), getUserIdAttribute()
  };

  final List<AccessIdRepresentationModel> accessIds =
      ldapTemplate.search(
          getUserSearchBase(),
          andFilter.encode(),
          SearchControls.SUBTREE_SCOPE,
          userAttributesToReturn,
          new UserContextMapper());
  LOGGER.debug("exit from searchUsersByAccessId. Retrieved the following users: {}.", accessIds);
  return accessIds;
}
 
Example #19
Source File: LdapTemplateAuthenticationITest.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
@Test
   @Category(NoAdTest.class)
public void testLookupAttemptingCallback() {
	AndFilter filter = new AndFilter();
	filter.and(new EqualsFilter("objectclass", "person")).and(new EqualsFilter("uid", "some.person3"));
	LookupAttemptingCallback callback = new LookupAttemptingCallback();
	assertThat(tested.authenticate("", filter.encode(), "password", callback)).isTrue();
}
 
Example #20
Source File: LdapTemplateAuthenticationITest.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
@Test(expected=IncorrectResultSizeDataAccessException.class)
   @Category(NoAdTest.class)
public void testAuthenticateWithFilterThatMatchesSeveralEntries() {
	AndFilter filter = new AndFilter();
	filter.and(new EqualsFilter("objectclass", "person")).and(new EqualsFilter("cn", "Some Person"));
	tested.authenticate("", filter.toString(), "password");
}
 
Example #21
Source File: LdapTemplateAuthenticationITest.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
@Test
   @Category(NoAdTest.class)
public void testAuthenticateWithFilterThatDoesNotMatchAnything() {
	AndFilter filter = new AndFilter();
	filter.and(new EqualsFilter("objectclass", "person")).and(
			new EqualsFilter("uid", "some.person.that.isnt.there"));
	assertThat(tested.authenticate("", filter.toString(), "password")).isFalse();
}
 
Example #22
Source File: LdapTemplateAuthenticationITest.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
@Test
   @Category(NoAdTest.class)
public void testAuthenticateWithInvalidPasswordAndCollectedException() {
	AndFilter filter = new AndFilter();
	filter.and(new EqualsFilter("objectclass", "person")).and(new EqualsFilter("uid", "some.person3"));
	final CollectingAuthenticationErrorCallback errorCallback = new CollectingAuthenticationErrorCallback();
	assertThat(tested.authenticate("", filter.toString(), "invalidpassword", errorCallback)).isFalse();
	final Exception error = errorCallback.getError();
	assertThat(error).as("collected error should not be null").isNotNull();
	assertThat(error instanceof AuthenticationException).as("expected org.springframework.ldap.AuthenticationException").isTrue();
	assertThat(error.getCause() instanceof javax.naming.AuthenticationException).as("expected javax.naming.AuthenticationException").isTrue();
}
 
Example #23
Source File: LdapTemplateAuthenticationITest.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
@Test(expected = AuthenticationException.class)
@Category(NoAdTest.class)
public void testAuthenticateWithLdapQueryAndInvalidPassword() {
    AndFilter filter = new AndFilter();
    filter.and(new EqualsFilter("objectclass", "person")).and(new EqualsFilter("uid", "some.person3"));
    tested.authenticate(query()
            .where("objectclass").is("person")
            .and("uid").is("some.person3"),
            "invalidpassword");
}
 
Example #24
Source File: LdapTemplateAuthenticationITest.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
@Test
   @Category(NoAdTest.class)
public void testAuthenticateWithInvalidPassword() {
	AndFilter filter = new AndFilter();
	filter.and(new EqualsFilter("objectclass", "person")).and(new EqualsFilter("uid", "some.person3"));
	assertThat(tested.authenticate("", filter.toString(), "invalidpassword")).isFalse();
}
 
Example #25
Source File: LdapUtil.java    From zstack with Apache License 2.0 5 votes vote down vote up
void findLdapDnMemberOfList(LdapTemplate ldapTemplate, String ldapDn, List<String> resultDnList, List<String> dnIgnoreList){
    if(dnIgnoreList.contains(ldapDn)){
        return;
    }

    AndFilter filter = new AndFilter();
    filter.and(new EqualsFilter(getMemberKey(), ldapDn));

    List<Object> groupList = ldapTemplate.search("", filter.toString(), new AbstractContextMapper<Object>() {
        @Override
        protected Object doMapFromContext(DirContextOperations ctx) {
            return ctx.getNameInNamespace();
        }
    });

    if(groupList.isEmpty()){
        dnIgnoreList.add(ldapDn);
        return;
    }

    for(Object groupObj : groupList){
        if(groupObj == null || !(groupObj instanceof String)){
            continue;
        }

        String groupDn = (String)groupObj;

        if(resultDnList.contains(groupDn)){
            continue;
        }

        resultDnList.add(groupDn);
        findLdapDnMemberOfList(ldapTemplate, groupDn, resultDnList, dnIgnoreList);
    }
}
 
Example #26
Source File: LdapTemplateAuthenticationITest.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
@Test
   @Category(NoAdTest.class)
public void testAuthenticate() {
	AndFilter filter = new AndFilter();
	filter.and(new EqualsFilter("objectclass", "person")).and(new EqualsFilter("uid", "some.person3"));
	assertThat(tested.authenticate("", filter.toString(), "password")).isTrue();
}
 
Example #27
Source File: LdapServiceImpl.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Override
public Group getGroup(String realm, String groupName) {
    DistinguishedName dn = new DistinguishedName("ou=" + realm);
    AndFilter filter = new AndFilter();
    filter.and(new EqualsFilter(OBJECTCLASS, groupObjectClass)).and(new EqualsFilter("cn", groupName));
    try {
        return (Group) ldapTemplate.searchForObject(dn, filter.toString(), new GroupContextMapper());
    } catch (EmptyResultDataAccessException e) {
        return null;
    }
}
 
Example #28
Source File: LdapServiceImpl.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public Collection<Group> getUserGroups(String realm, String uid) {
    DistinguishedName dn = new DistinguishedName("ou=" + realm);
    AndFilter filter = new AndFilter();
    filter.and(new EqualsFilter(OBJECTCLASS, groupObjectClass)).and(new EqualsFilter(groupSearchAttribute, uid));
    List<Group> groups = ldapTemplate.search(dn, filter.toString(), new GroupContextMapper());
    return groups;
}
 
Example #29
Source File: UserService.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param realm
 *            The realm under which the user exists
 * @param userId
 *            The id of the user
 * @return
 */
public User getUser(String realm, String userId) {
    AndFilter filter = new AndFilter();
    filter.and(new EqualsFilter("objectclass", userObjectClass)).and(new EqualsFilter(userSearchAttribute, userId));
    DistinguishedName dn = new DistinguishedName("ou=" + realm);
    PersonContextMapper pcm = new PersonContextMapper();
    boolean needAdditionalAttributes = (realm != null && realm.equals(sliAdminRealmName));
    pcm.setAddAttributes(needAdditionalAttributes);
    return (User) ldapTemplate.searchForObject(dn, filter.toString(), pcm);
}
 
Example #30
Source File: LdapUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static List<String> getAttributeOfEntries(
    LdapTemplate ldapTemplate, String baseDN,
    String objectClass, List<Filter> filters,
    String searchAttribute) {

    List<String> ldapAttributes = null;

    AttributesMapper<Object> mapper =
        new AttributesMapper<Object>() {
        public Object mapFromAttributes(Attributes attrs) throws NamingException {
            NamingEnumeration<? extends Attribute> attrEnum = attrs.getAll();
            while (attrEnum.hasMore()) {
                return attrEnum.next().get();
            }
            return null;
        }
    };

    String[] searchAttributes = new String[] {searchAttribute};

    List<?> result = null;
    AndFilter filter = new AndFilter();
    filter.and(new EqualsFilter("objectclass", objectClass));
    if (filters != null) {
        for (Filter f : filters) {
            filter.and(f);
        }
    }

    result = ldapTemplate.search((baseDN == null) ? "" : baseDN, filter.toString(),
        SearchControls.SUBTREE_SCOPE, searchAttributes, mapper);
    if (result != null && !result.isEmpty()) {
        ldapAttributes = CastUtils.cast((List<?>)result);
    }

    return ldapAttributes;
}