org.springframework.ldap.filter.AndFilter Java Examples

The following examples show how to use org.springframework.ldap.filter.AndFilter. 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: 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 #2
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 #3
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 #4
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 #5
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 #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: LdapManagerImpl.java    From zstack with Apache License 2.0 6 votes vote down vote up
private void handle(APIGetCandidateLdapEntryForBindingMsg msg) {
    APIGetLdapEntryReply reply = new APIGetLdapEntryReply();

    AndFilter andFilter = new AndFilter();
    andFilter.and(new HardcodedFilter(msg.getLdapFilter()));

    List<String> boundLdapEntryList = Q.New(LdapAccountRefVO.class)
            .select(LdapAccountRefVO_.ldapUid)
            .listValues();

    List<Object> result = ldapUtil.searchLdapEntry(andFilter.toString(), msg.getLimit(), new ResultFilter() {
        @Override
        public boolean needSelect(String dn) {
            return !boundLdapEntryList.contains(dn);
        }
    });

    reply.setInventories(result);

    bus.reply(msg, reply);
}
 
Example #8
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 #9
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 #10
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 #11
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 #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: 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 #14
Source File: DefaultObjectDirectoryMapper.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
@Override
public Filter filterFor(Class<?> clazz, Filter baseFilter) {
    Filter ocFilter = getEntityData(clazz).ocFilter;

    if(baseFilter == null) {
        return ocFilter;
    }

    AndFilter andFilter = new AndFilter();
    return andFilter.append(ocFilter).append(baseFilter);
}
 
Example #15
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 #16
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 #17
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 #18
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 #19
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 #20
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 #21
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 #22
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;
}
 
Example #23
Source File: LdapUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static Map<String, Attribute> getAttributesOfEntry(LdapTemplate ldapTemplate, String baseDN,
    String objectClass, String filterAttributeName, String filterAttributeValue,
    String[] searchAttributes) {

    Map<String, Attribute> ldapAttributes = null;

    AttributesMapper<Map<String, Attribute>> mapper =
        new AttributesMapper<Map<String, Attribute>>() {
            public Map<String, Attribute> mapFromAttributes(Attributes attrs) throws NamingException {
                Map<String, Attribute> map = new HashMap<>();
                NamingEnumeration<? extends Attribute> attrEnum = attrs.getAll();
                while (attrEnum.hasMore()) {
                    Attribute att = attrEnum.next();
                    map.put(att.getID(), att);
                }
                return map;
            }
        };

    List<?> result = null;
    AndFilter filter = new AndFilter();
    filter.and(
            new EqualsFilter("objectclass", objectClass)).and(
                    new EqualsFilter(filterAttributeName, filterAttributeValue));

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

    return ldapAttributes;
}
 
Example #24
Source File: UserServiceImpl.java    From cxf with Apache License 2.0 5 votes vote down vote up
private static Map<String, Attribute> getAttributesOfEntry(LdapTemplate ldapTemplate, String baseDN,
                                                           String objectClass, String searchFilter,
                                                           String[] searchAttributes) {

    Map<String, Attribute> ldapAttributes = null;

    AttributesMapper<Map<String, Attribute>> mapper =
        new AttributesMapper<Map<String, Attribute>>() {
        public Map<String, Attribute> mapFromAttributes(Attributes attrs) throws NamingException {
            Map<String, Attribute> map = new HashMap<>();
            NamingEnumeration<? extends Attribute> attrEnum = attrs.getAll();
            while (attrEnum.hasMore()) {
                Attribute att = attrEnum.next();
                map.put(att.getID(), att);
            }
            return map;
        }
    };

    AndFilter filter = new AndFilter();
    filter.and(new EqualsFilter("objectclass", objectClass)).and(new HardcodedFilter(searchFilter));

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

    return ldapAttributes;
}
 
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: LdapUpgradeExtension.java    From zstack with Apache License 2.0 5 votes vote down vote up
private void update(LdapTemplate ldapTemplate, LdapAccountRefVO ref){
    String uid = ref.getLdapUid();

    AndFilter filter = new AndFilter();
    filter.and(new EqualsFilter("uid", ref.getLdapUid()));

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

    if(result.size() == 0){
        logger.error(String.format("Can not find ldapUid[%s] dn", uid));
        return;
    }

    if(result.size() > 1){
        logger.error(String.format("ldapUid[%s] More than one dn result", uid));
        return;
    }

    String dn = result.get(0).toString();
    ref.setLdapUid(dn);
    dbf.update(ref);
    logger.info(String.format("update ldapUid[%s] to ldapDn[%s] success", uid, dn));
}
 
Example #27
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 #28
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 #29
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 #30
Source File: ChoerodonAuthenticationProvider.java    From oauth-server with Apache License 2.0 5 votes vote down vote up
private String accountAsUserDn2Authentication(String loginName, LdapE ldap, LdapContextSource contextSource, AndFilter filter) {
    contextSource.setUserDn(ldap.getAccount());
    contextSource.setPassword(ldap.getPassword());
    contextSource.afterPropertiesSet();
    LdapTemplate template = new LdapTemplate(contextSource);
    if (DirectoryType.MICROSOFT_ACTIVE_DIRECTORY.value().equals(ldap.getDirectoryType())) {
        template.setIgnorePartialResultException(true);
    }
    String userDn = null;
    try {
        List<String> names =
                template.search(
                        query()
                                .searchScope(SearchScope.SUBTREE)
                                .filter(filter),
                        new AbstractContextMapper() {
                            @Override
                            protected Object doMapFromContext(DirContextOperations ctx) {
                                return ctx.getNameInNamespace();
                            }
                        });
        userDn = getUserDn(names, ldap.getLoginNameField(), loginName);
    } catch (Exception e) {
        LOG.error("use ldap account as userDn and password to authentication but search failed, filter {}," +
                " maybe the account or password is illegal, and check for the ldap config, exception {}", filter, e);
    }
    return userDn;
}