org.springframework.ldap.query.LdapQueryBuilder Java Examples

The following examples show how to use org.springframework.ldap.query.LdapQueryBuilder. 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: EmbeddedLdapServerFactoryBeanTest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@Test
public void testServerStartup() throws Exception {
    ctx = new ClassPathXmlApplicationContext("/applicationContext-ldifPopulator.xml");
    LdapTemplate ldapTemplate = ctx.getBean(LdapTemplate.class);
    assertThat(ldapTemplate).isNotNull();

    List<String> list = ldapTemplate.search(
            LdapQueryBuilder.query().where("objectclass").is("person"),
            new AttributesMapper<String>() {
                public String mapFromAttributes(Attributes attrs)
                        throws NamingException {
                    return (String) attrs.get("cn").get();
                }
            });
    assertThat(list.size()).isEqualTo(5);
}
 
Example #2
Source File: TestContextSourceFactoryBeanTest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@Test
public void testServerStartup() throws Exception {
    ctx = new ClassPathXmlApplicationContext("/applicationContext-testContextSource.xml");
    LdapTemplate ldapTemplate = ctx.getBean(LdapTemplate.class);
    assertThat(ldapTemplate).isNotNull();

    List<String> list = ldapTemplate.search(
            LdapQueryBuilder.query().where("objectclass").is("person"),
            new AttributesMapper<String>() {
                public String mapFromAttributes(Attributes attrs)
                        throws NamingException {
                    return (String) attrs.get("cn").get();
                }
            });
    assertThat(list.size()).isEqualTo(5);
}
 
Example #3
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 #4
Source File: LdapAuthRepositoryCustomImpl.java    From Spring-5.0-Projects with MIT License 6 votes vote down vote up
private String getDnForUser(String uid) {
  List<String> result = ldapTemplate.search(
      LdapQueryBuilder.query().where("uid").is(uid),
      new AbstractContextMapper<String>() {
         protected String doMapFromContext(DirContextOperations ctx) {
        	 logger.info("######## NameInNamespace -->"+ctx.getNameInNamespace());
            return ctx.getNameInNamespace();
         }
      });

  if(result.size() != 1) {
    throw new RuntimeException("User not found or not unique");
  }

  return result.get(0);
}
 
Example #5
Source File: GatekeeperLdapLookupService.java    From Gatekeeper with Apache License 2.0 6 votes vote down vote up
@Override
public List<GatekeeperSearchUserEntry> searchForUsers(String queryStr){
    logger.info("Searching for users matching "+queryStr);
    return ldapTemplate.search(
            LdapQueryBuilder.query()
                    .base(ldapProperties.getUsersBase())
                    .countLimit(10)
                    .searchScope(SearchScope.SUBTREE)
                    .where("objectClass")
                    .is(ldapObjectClass)
                    .and(LdapQueryBuilder.query()
                            .where(ldapUserId)
                            .like("*"+queryStr+"*")
                            .or(ldapUserName)
                            .like("*"+queryStr+"*")), getAttributesMapper());
}
 
Example #6
Source File: EmbeddedLdapServerFactoryBeanTest.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
@Test
  public void testServerStartup() throws Exception {
      ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("/applicationContext.xml");
      LdapTemplate ldapTemplate = ctx.getBean(LdapTemplate.class);
      assertNotNull(ldapTemplate);

List<String> list = ldapTemplate.search(
		LdapQueryBuilder.query().where("objectclass").is("person"),
		new AttributesMapper<String>() {
			public String mapFromAttributes(Attributes attrs)
					throws NamingException {
				return (String) attrs.get("cn").get();
			}
		});
      assertEquals(5, list.size());
  }
 
Example #7
Source File: LdapTemplateTest.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {

	// Setup ContextSource mock
	contextSourceMock = mock(ContextSource.class);
	// Setup LdapContext mock
	dirContextMock = mock(LdapContext.class);
	// Setup NamingEnumeration mock
	namingEnumerationMock = mock(NamingEnumeration.class);
	// Setup Name mock
	nameMock = LdapUtils.emptyLdapName();
	// Setup Handler mock
	handlerMock = mock(NameClassPairCallbackHandler.class);
	contextMapperMock = mock(ContextMapper.class);
	attributesMapperMock = mock(AttributesMapper.class);
	contextExecutorMock = mock(ContextExecutor.class);
	searchExecutorMock = mock(SearchExecutor.class);
	dirContextProcessorMock = mock(DirContextProcessor.class);
	dirContextOperationsMock = mock(DirContextOperations.class);
	authenticatedContextMock = mock(DirContext.class);
	entryContextCallbackMock = mock(AuthenticatedLdapEntryContextCallback.class);
       odmMock = mock(ObjectDirectoryMapper.class);
	query = LdapQueryBuilder.query().base("ou=spring").filter("ou=user");
	authContextMapperMock = mock(AuthenticatedLdapEntryContextMapper.class);

       tested = new LdapTemplate(contextSourceMock);
       tested.setObjectDirectoryMapper(odmMock);
}
 
Example #8
Source File: LdapIdentityLookup.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
@Override
public Collection<User> search(String query) {
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    try {
        Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
        String usersSearchFilter = environment.getProperty("lookup.user.filter", LDAP_DEFAULT_LOOKUP_FILTER);
        String hardcodedFilter = usersSearchFilter.replaceAll("\\{0}", LdapUtils.addWhitespaceWildcards(query));

        LdapQuery ldapQuery = LdapQueryBuilder
                .query()
                .base(baseDn)
                .countLimit(20)
                .timeLimit(5000)
                .searchScope(SearchScope.SUBTREE)
                .attributes(
                        LDAP_ATTRIBUTE_GIVENNAME,
                        LDAP_ATTRIBUTE_SURNAME,
                        LDAP_ATTRIBUTE_MAIL,
                        LDAP_ATTRIBUTE_DISPLAYNAME)
                .filter(new HardcodedFilter(hardcodedFilter));

        return ldapTemplate.search(ldapQuery, USER_CONTEXT_MAPPER);
    } catch(LimitExceededException lee) {
        LOGGER.info("Too much results while searching for [{}]. Returns an empty list.", query);
        return Collections.emptyList();
    } catch(CommunicationException ce) {
        LOGGER.error("LDAP server is not reachable.");
        return Collections.emptyList();
    } finally {
        Thread.currentThread().setContextClassLoader(classLoader);
    }
}
 
Example #9
Source File: GatekeeperOpenLDAPAuthorizationService.java    From Gatekeeper with Apache License 2.0 5 votes vote down vote up
protected GatekeeperUserEntry loadUser(String userName){
    logger.info("Loading info for " + userName);
    LdapQuery query = LdapQueryBuilder.query()
            .base(ldapProperties.getUsersBase()).countLimit(1)
            .searchScope(SearchScope.SUBTREE)
            .attributes(ldapUserId, ldapUserDn, ldapUserEmail, ldapUserName)
            .where("objectClass")
            .is(ldapObjectClass)
            .and(ldapUserId)
            .is(userName);
    List<GatekeeperUserEntry> subjects = ldapTemplate.search(query, getAttributesMapper());

    if (subjects != null && subjects.size() > 0) {
        return subjects.get(0);
        //check to see if account is test account (only if testUsersBase is provided)
    } else if(ldapProperties.getTestUsersBase() != null) {
        query = LdapQueryBuilder.query()
                .base(ldapProperties.getTestUsersBase()).countLimit(1)
                .searchScope(SearchScope.SUBTREE)
                .attributes(ldapUserId, ldapUserDn, ldapUserEmail, ldapUserName)
                .where("objectCategory")
                .is(ldapObjectClass)
                .and(ldapUserId)
                .is(userName);
        subjects = ldapTemplate.search(query, getAttributesMapper());
        //return null;
        if (subjects != null && subjects.size() > 0) {
            return subjects.get(0);
        }
    }
    return null;
}
 
Example #10
Source File: GatekeeperActiveDirectoryLDAPAuthorizationService.java    From Gatekeeper with Apache License 2.0 5 votes vote down vote up
@Override
protected Set<String> loadUserMemberships(String userName){
    {
        Optional<GatekeeperUserEntry> user = userCache.getUnchecked(userName);
        String userDn = user.get().getDn();

        LdapQuery memberOfApplication = LdapQueryBuilder.query()
                .base(ldapUserGroupsBase)
                .searchScope(SearchScope.SUBTREE)
                .attributes(ldapUserCn, ldapUserDn)
                .filter("(member:" + LDAP_MATCHING_RULE_IN_CHAIN + ":=" + userDn + ")");

        return new HashSet<>(ldapTemplate.search(memberOfApplication, getStringAttributesMapper(ldapUserCn)));
    }
}
 
Example #11
Source File: LdapAuthService.java    From Spring-5.0-Projects with MIT License 5 votes vote down vote up
public void deleteUser(String userName) {
	
	Optional<LdapAuthUser> ldapAuthUserOptional = ldapAuthRepository.findOne(LdapQueryBuilder.query().where("uid").is(userName));
	if(ldapAuthUserOptional.isPresent()) {
		ldapAuthRepository.delete(ldapAuthUserOptional.get());
	}else {
		logger.info("User with username "+userName+" does not exist ");
	}
}
 
Example #12
Source File: LdapAuthService.java    From Spring-5.0-Projects with MIT License 5 votes vote down vote up
public LdapAuthUser getUser(String userName) {
	
	Optional<LdapAuthUser> ldapAuthUserOptional = ldapAuthRepository.
				findOne(LdapQueryBuilder.query().where("uid").is(userName));
	if(ldapAuthUserOptional.isPresent()) {
		return ldapAuthUserOptional.get();
	}else {
		return null;
	}
}
 
Example #13
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 #14
Source File: LdapAuthRepositoryCustomImpl.java    From Spring-5.0-Projects with MIT License 5 votes vote down vote up
@Override
public boolean authenticateLdapUserWithLdapQuery(String userName, String password) {
	
	try {
	 ldapTemplate.authenticate(LdapQueryBuilder.query().where("uid").is(userName), password);
	 return true;
	}catch(Exception e) {
		logger.error("Exception occuired while authenticating user with user name "+userName,e.getMessage(),e);
	}
	return false;
}
 
Example #15
Source File: GatekeeperOpenLDAPAuthorizationService.java    From Gatekeeper with Apache License 2.0 4 votes vote down vote up
protected Set<String> loadUserMemberships(String userName){
    Pattern cnPattern = Pattern.compile("cn=([- _A-Za-z0-9]+)", Pattern.CASE_INSENSITIVE);

    logger.info("Checking Memberships for " +userName );
    Set<String> memberships = new HashSet<>();
    String memberof = "memberOf";
    LdapQuery query = LdapQueryBuilder.query()
            .base(ldapProperties.getUsersBase()).countLimit(1000)
            .searchScope(SearchScope.SUBTREE)
            .attributes(memberof)
            .where("objectClass")
            .is(ldapObjectClass)
            .and(ldapUserId)
            .is(userName);


    LinkedList<String[]> subjects = (LinkedList<String[]>)ldapTemplate.search(query, new OpenLdapMembershipsMapper());

    if (subjects == null || subjects.size() == 0) {
        if(ldapProperties.getTestUsersBase() != null) {
            query = LdapQueryBuilder.query()
                    .base(ldapProperties.getTestUsersBase()).countLimit(1000)
                    .searchScope(SearchScope.SUBTREE)
                    .attributes("memberOf")
                    .where("objectClass")
                    .is(ldapObjectClass)
                    .and(ldapUserId)
                    .is(userName);
            subjects = (LinkedList<String[]>) ldapTemplate.search(query, new OpenLdapMembershipsMapper());
        }
    }

    HashSet<String> extracted = new HashSet<>();

    Arrays.asList(subjects.getFirst()).forEach(item -> {
        Matcher m = cnPattern.matcher(item);
        if(m.find()) {
            extracted.add(m.group(1));
        }
    });

    return extracted;
}
 
Example #16
Source File: LdapAuthRepositoryCustomImpl.java    From Spring-5.0-Projects with MIT License 4 votes vote down vote up
@Override
public List<LdapAuthUser> findBySurname(String surName) {
	return ldapTemplate.find(LdapQueryBuilder.query().where("sn").is(surName), LdapAuthUser.class);
}
 
Example #17
Source File: LdapAuthRepositoryCustomImpl.java    From Spring-5.0-Projects with MIT License 4 votes vote down vote up
@Override
public LdapAuthUser findByUid(String uid) {
	return ldapTemplate.findOne(LdapQueryBuilder.query().where("uid").is(uid), LdapAuthUser.class);
}
 
Example #18
Source File: LdapAuthRepositoryCustomImpl.java    From Spring-5.0-Projects with MIT License 4 votes vote down vote up
@Override
public List<LdapAuthUser> findByMatchingUserName(String userName) {
	return ldapTemplate.find(LdapQueryBuilder.query().where("uid").like(userName), LdapAuthUser.class);
}
 
Example #19
Source File: LdapAuthRepositoryCustomImpl.java    From Spring-5.0-Projects with MIT License 4 votes vote down vote up
@Override
public LdapAuthUser findByUserName(String userName) {
	return ldapTemplate.findOne(LdapQueryBuilder.query().where("uid").is(userName), LdapAuthUser.class);
}