org.springframework.ldap.query.LdapQuery Java Examples

The following examples show how to use org.springframework.ldap.query.LdapQuery. 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: 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 #2
Source File: KnoxSSOAuthenticationFilterTest.java    From metron with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void getAuthenticationShouldProperlyPopulateAuthentication() {
  LdapTemplate ldapTemplate = mock(LdapTemplate.class);
  KnoxSSOAuthenticationFilter knoxSSOAuthenticationFilter = spy(new KnoxSSOAuthenticationFilter("ou=people,dc=hadoop,dc=apache,dc=org",
          mock(Path.class),
          "knoxKeyString",
          "knoxCookie",
          ldapTemplate
  ));

  HttpServletRequest request = mock(HttpServletRequest.class);

  when(ldapTemplate.search(any(LdapQuery.class), any(AttributesMapper.class))).thenReturn(Arrays.asList("USER", "ADMIN"));

  Authentication authentication = knoxSSOAuthenticationFilter.getAuthentication("userName", request);
  Object[] grantedAuthorities = authentication.getAuthorities().toArray();
  assertEquals("ROLE_USER", grantedAuthorities[0].toString());
  assertEquals("ROLE_ADMIN", grantedAuthorities[1].toString());
  assertEquals("userName", authentication.getName());
}
 
Example #3
Source File: LdapTemplate.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
private SearchControls searchControlsForQuery(LdapQuery query, boolean returnObjFlag) {
    SearchControls searchControls = getDefaultSearchControls(
            defaultSearchScope,
            returnObjFlag,
            query.attributes());

    if(query.searchScope() != null) {
        searchControls.setSearchScope(query.searchScope().getId());
    }

    if(query.countLimit() != null) {
        searchControls.setCountLimit(query.countLimit());
    }

    if(query.timeLimit() != null) {
        searchControls.setTimeLimit(query.timeLimit());
    }
    return searchControls;
}
 
Example #4
Source File: LdapTemplate.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public DirContextOperations searchForContext(LdapQuery query) {
    return searchForObject(query, new ContextMapper<DirContextOperations>() {
        @Override
        public DirContextOperations mapFromContext(Object ctx) throws javax.naming.NamingException {
            return (DirContextOperations) ctx;
        }
    });
}
 
Example #5
Source File: LdapTemplate.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void authenticate(LdapQuery query, String password) {
    authenticate(query,
            password,
            new NullAuthenticatedLdapEntryContextCallback());
}
 
Example #6
Source File: LdapTemplate.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public <T> T authenticate(LdapQuery query, String password, AuthenticatedLdapEntryContextMapper<T> mapper) {
    SearchControls searchControls = searchControlsForQuery(query, RETURN_OBJ_FLAG);
    ReturningAuthenticatedLdapEntryContext<T> mapperCallback =
            new ReturningAuthenticatedLdapEntryContext<T>(mapper);
    CollectingAuthenticationErrorCallback errorCallback =
            new CollectingAuthenticationErrorCallback();

    AuthenticationStatus authenticationStatus = authenticate(query.base(),
            query.filter().encode(),
            password,
            searchControls,
            mapperCallback,
            errorCallback);

    if(errorCallback.hasError()) {
        Exception error = errorCallback.getError();

        if (error instanceof NamingException) {
            throw (NamingException) error;
        } else {
            throw new UncategorizedLdapException(error);
        }
    } else if(AuthenticationStatus.EMPTYRESULT == authenticationStatus) {
    	throw new EmptyResultDataAccessException(1);
    } else if(!authenticationStatus.isSuccess()) {
        throw new AuthenticationException();
    }

    return mapperCallback.collectedObject;
}
 
Example #7
Source File: LdapTemplate.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void search(LdapQuery query, NameClassPairCallbackHandler callbackHandler) {
    SearchControls searchControls = searchControlsForQuery(query, DONT_RETURN_OBJ_FLAG);
    search(query.base(),
            query.filter().encode(),
            searchControls,
            callbackHandler);
}
 
Example #8
Source File: LdapTemplate.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public <T> List<T> search(LdapQuery query, ContextMapper<T> mapper) {
    SearchControls searchControls = searchControlsForQuery(query, RETURN_OBJ_FLAG);

    return search(query.base(),
            query.filter().encode(),
            searchControls,
            mapper);

}
 
Example #9
Source File: LdapTemplate.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public <T> List<T> search(LdapQuery query, AttributesMapper<T> mapper) {
    SearchControls searchControls = searchControlsForQuery(query, DONT_RETURN_OBJ_FLAG);

    return search(query.base(),
            query.filter().encode(),
            searchControls,
            mapper);
}
 
Example #10
Source File: LdapOperationsTest.java    From herd with Apache License 2.0 5 votes vote down vote up
@Test
public void testSearch()
{
    // Create and initialize an LDAP context source.
    LdapContextSource contextSource = new LdapContextSource();
    contextSource.setUrl(LDAP_URL);
    contextSource.setBase(LDAP_BASE);
    contextSource.setUserDn(LDAP_USER_DN);
    contextSource.setPassword(PASSWORD);
    contextSource.afterPropertiesSet();

    // Create an LDAP template.
    LdapTemplate ldapTemplate = new LdapTemplate(contextSource);

    // Create an LDAP query.
    LdapQuery ldapQuery = query().where((String) ConfigurationValue.LDAP_ATTRIBUTE_USER_ID.getDefaultValue()).is(USER_ID);

    // Create a subject matter expert contact details mapper.
    SubjectMatterExpertDaoImpl.SubjectMatterExpertContactDetailsMapper subjectMatterExpertContactDetailsMapper =
        new SubjectMatterExpertDaoImpl.SubjectMatterExpertContactDetailsMapper((String) ConfigurationValue.LDAP_ATTRIBUTE_USER_FULL_NAME.getDefaultValue(),
            (String) ConfigurationValue.LDAP_ATTRIBUTE_USER_JOB_TITLE.getDefaultValue(),
            (String) ConfigurationValue.LDAP_ATTRIBUTE_USER_EMAIL_ADDRESS.getDefaultValue(),
            (String) ConfigurationValue.LDAP_ATTRIBUTE_USER_TELEPHONE_NUMBER.getDefaultValue());

    // Gets information for the specified subject matter expert.
    List<SubjectMatterExpertContactDetails> result = ldapOperations.search(ldapTemplate, ldapQuery, subjectMatterExpertContactDetailsMapper);

    // Validate the results.
    assertEquals(
        Collections.singletonList(new SubjectMatterExpertContactDetails(USER_FULL_NAME, USER_JOB_TITLE, USER_EMAIL_ADDRESS, USER_TELEPHONE_NUMBER)),
        result);
}
 
Example #11
Source File: LdapTemplate.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public <T> T searchForObject(LdapQuery query, ContextMapper<T> mapper) {
    SearchControls searchControls = searchControlsForQuery(query, DONT_RETURN_OBJ_FLAG);

    return searchForObject(query.base(),
            query.filter().encode(),
            searchControls,
            mapper);
}
 
Example #12
Source File: LdapTemplate.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public <T> T findOne(LdapQuery query, Class<T> clazz) {
    List<T> result = find(query, clazz);

    if (result.size() == 0) {
        throw new EmptyResultDataAccessException(1);
    }
    else if (result.size() != 1) {
        throw new IncorrectResultSizeDataAccessException(1, result.size());
    }

    return result.get(0);
}
 
Example #13
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 #14
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 #15
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 #16
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 #17
Source File: LdapTemplate.java    From spring-ldap with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public <T> List<T> find(LdapQuery query, Class<T> clazz) {
    SearchControls searchControls = searchControlsForQuery(query, RETURN_OBJ_FLAG);
    return find(query.base(), query.filter(), searchControls, clazz);
}
 
Example #18
Source File: MockLdapOperations.java    From herd with Apache License 2.0 4 votes vote down vote up
/**
 * Executes {@link org.springframework.ldap.core.LdapTemplate#search(org.springframework.ldap.query.LdapQuery,
 * org.springframework.ldap.core.AttributesMapper)}.
 *
 * @param ldapTemplate the LDAP template to use
 * @param query the LDAP query specification
 * @param mapper the <code>Attributes</code> to supply all found Attributes to
 *
 * @return the predefined LDAP search results constructed by the given {@link org.springframework.ldap.core.AttributesMapper}
 */
@Override
public <T> List<T> search(LdapTemplate ldapTemplate, LdapQuery query, AttributesMapper<T> mapper)
{
    // Create an empty results list.
    List<T> results = new ArrayList<>();

    // Get the query filter as a string.
    String filter = query.filter().toString();

    // Check if we need to respond with the predefined result.
    if (!filter.contains(MOCK_USER_ID_USER_NO_EXISTS))
    {
        // Create attributes object with ignoreCase flag set to "true".
        BasicAttributes attributes = new BasicAttributes(true);

        // Populate the attributes with predefined set of results.
        attributes
            .put(new BasicAttribute(configurationHelper.getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_FULL_NAME), AbstractDaoTest.USER_FULL_NAME));
        attributes
            .put(new BasicAttribute(configurationHelper.getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_JOB_TITLE), AbstractDaoTest.USER_JOB_TITLE));
        attributes.put(
            new BasicAttribute(configurationHelper.getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_EMAIL_ADDRESS), AbstractDaoTest.USER_EMAIL_ADDRESS));

        // Check if it is OK to add the user phone number attribute.
        if (!filter.contains(MOCK_USER_ID_ATTRIBUTE_USER_TELEPHONE_NUMBER_NO_EXISTS))
        {
            attributes.put(new BasicAttribute(configurationHelper.getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_TELEPHONE_NUMBER),
                AbstractDaoTest.USER_TELEPHONE_NUMBER));
        }

        // Map the results.
        try
        {
            results.add(mapper.mapFromAttributes(attributes));
        }
        catch (NamingException e)
        {
            // Do nothing.
        }
    }

    // Return the results.
    return results;
}
 
Example #19
Source File: SubjectMatterExpertDaoImplTest.java    From herd with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetSubjectMatterExpertByKeyUserNoExists() throws Exception
{
    // Create a subject matter expert key.
    SubjectMatterExpertKey subjectMatterExpertKey = new SubjectMatterExpertKey(USER_ID);

    // Create subject matter expert contact details initialised with test data.
    SubjectMatterExpertContactDetails subjectMatterExpertContactDetails =
        new SubjectMatterExpertContactDetails(USER_FULL_NAME, USER_JOB_TITLE, USER_EMAIL_ADDRESS, USER_TELEPHONE_NUMBER);

    // Mock the external calls.
    when(configurationHelper.getProperty(ConfigurationValue.LDAP_URL)).thenReturn(LDAP_URL);
    when(configurationHelper.getProperty(ConfigurationValue.LDAP_BASE)).thenReturn(LDAP_BASE);
    when(configurationHelper.getProperty(ConfigurationValue.LDAP_USER_DN)).thenReturn(LDAP_USER_DN);
    when(configurationHelper.getProperty(ConfigurationValue.CREDSTASH_HERD_ENCRYPTION_CONTEXT)).thenReturn(CREDSTASH_ENCRYPTION_CONTEXT);
    when(configurationHelper.getProperty(ConfigurationValue.LDAP_USER_CREDENTIAL_NAME)).thenReturn(USER_CREDENTIAL_NAME);
    when(credStashHelper.getCredentialFromCredStash(CREDSTASH_ENCRYPTION_CONTEXT, USER_CREDENTIAL_NAME)).thenReturn(PASSWORD);
    when(configurationHelper.getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_ID)).thenReturn(LDAP_ATTRIBUTE_USER_ID);
    when(configurationHelper.getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_FULL_NAME)).thenReturn(LDAP_ATTRIBUTE_USER_FULL_NAME);
    when(configurationHelper.getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_JOB_TITLE)).thenReturn(LDAP_ATTRIBUTE_USER_JOB_TITLE);
    when(configurationHelper.getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_EMAIL_ADDRESS)).thenReturn(LDAP_ATTRIBUTE_USER_EMAIL_ADDRESS);
    when(configurationHelper.getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_TELEPHONE_NUMBER)).thenReturn(LDAP_ATTRIBUTE_USER_TELEPHONE_NUMBER);
    when(
        ldapOperations.search(any(LdapTemplate.class), any(LdapQuery.class), any(SubjectMatterExpertDaoImpl.SubjectMatterExpertContactDetailsMapper.class)))
        .thenReturn(Collections.emptyList());

    // Call the method under test.
    SubjectMatterExpertContactDetails result = subjectMatterExpertDaoImpl.getSubjectMatterExpertByKey(subjectMatterExpertKey);

    // Validate the results.
    assertNull(result);

    // Verify the external calls.
    verify(configurationHelper).getProperty(ConfigurationValue.LDAP_URL);
    verify(configurationHelper).getProperty(ConfigurationValue.LDAP_BASE);
    verify(configurationHelper).getProperty(ConfigurationValue.LDAP_USER_DN);
    verify(configurationHelper).getProperty(ConfigurationValue.CREDSTASH_HERD_ENCRYPTION_CONTEXT);
    verify(configurationHelper).getProperty(ConfigurationValue.LDAP_USER_CREDENTIAL_NAME);
    verify(credStashHelper).getCredentialFromCredStash(CREDSTASH_ENCRYPTION_CONTEXT, USER_CREDENTIAL_NAME);
    verify(configurationHelper).getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_ID);
    verify(configurationHelper).getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_FULL_NAME);
    verify(configurationHelper).getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_JOB_TITLE);
    verify(configurationHelper).getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_EMAIL_ADDRESS);
    verify(configurationHelper).getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_TELEPHONE_NUMBER);
    verify(ldapOperations)
        .search(any(LdapTemplate.class), any(LdapQuery.class), any(SubjectMatterExpertDaoImpl.SubjectMatterExpertContactDetailsMapper.class));
    verifyNoMoreInteractionsHelper();
}
 
Example #20
Source File: SubjectMatterExpertDaoImplTest.java    From herd with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetSubjectMatterExpertByKey() throws Exception
{
    // Create a subject matter expert key.
    SubjectMatterExpertKey subjectMatterExpertKey = new SubjectMatterExpertKey(USER_ID);

    // Create subject matter expert contact details initialised with test data.
    SubjectMatterExpertContactDetails subjectMatterExpertContactDetails =
        new SubjectMatterExpertContactDetails(USER_FULL_NAME, USER_JOB_TITLE, USER_EMAIL_ADDRESS, USER_TELEPHONE_NUMBER);

    // Mock the external calls.
    when(configurationHelper.getProperty(ConfigurationValue.LDAP_URL)).thenReturn(LDAP_URL);
    when(configurationHelper.getProperty(ConfigurationValue.LDAP_BASE)).thenReturn(LDAP_BASE);
    when(configurationHelper.getProperty(ConfigurationValue.LDAP_USER_DN)).thenReturn(LDAP_USER_DN);
    when(configurationHelper.getProperty(ConfigurationValue.CREDSTASH_HERD_ENCRYPTION_CONTEXT)).thenReturn(CREDSTASH_ENCRYPTION_CONTEXT);
    when(configurationHelper.getProperty(ConfigurationValue.LDAP_USER_CREDENTIAL_NAME)).thenReturn(USER_CREDENTIAL_NAME);
    when(credStashHelper.getCredentialFromCredStash(CREDSTASH_ENCRYPTION_CONTEXT, USER_CREDENTIAL_NAME)).thenReturn(PASSWORD);
    when(configurationHelper.getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_ID)).thenReturn(LDAP_ATTRIBUTE_USER_ID);
    when(configurationHelper.getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_FULL_NAME)).thenReturn(LDAP_ATTRIBUTE_USER_FULL_NAME);
    when(configurationHelper.getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_JOB_TITLE)).thenReturn(LDAP_ATTRIBUTE_USER_JOB_TITLE);
    when(configurationHelper.getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_EMAIL_ADDRESS)).thenReturn(LDAP_ATTRIBUTE_USER_EMAIL_ADDRESS);
    when(configurationHelper.getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_TELEPHONE_NUMBER)).thenReturn(LDAP_ATTRIBUTE_USER_TELEPHONE_NUMBER);
    when(
        ldapOperations.search(any(LdapTemplate.class), any(LdapQuery.class), any(SubjectMatterExpertDaoImpl.SubjectMatterExpertContactDetailsMapper.class)))
        .thenReturn(Collections.singletonList(subjectMatterExpertContactDetails));

    // Call the method under test.
    SubjectMatterExpertContactDetails result = subjectMatterExpertDaoImpl.getSubjectMatterExpertByKey(subjectMatterExpertKey);

    // Validate the results.
    assertEquals(subjectMatterExpertContactDetails, result);

    // Verify the external calls.
    verify(configurationHelper).getProperty(ConfigurationValue.LDAP_URL);
    verify(configurationHelper).getProperty(ConfigurationValue.LDAP_BASE);
    verify(configurationHelper).getProperty(ConfigurationValue.LDAP_USER_DN);
    verify(configurationHelper).getProperty(ConfigurationValue.CREDSTASH_HERD_ENCRYPTION_CONTEXT);
    verify(configurationHelper).getProperty(ConfigurationValue.LDAP_USER_CREDENTIAL_NAME);
    verify(credStashHelper).getCredentialFromCredStash(CREDSTASH_ENCRYPTION_CONTEXT, USER_CREDENTIAL_NAME);
    verify(configurationHelper).getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_ID);
    verify(configurationHelper).getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_FULL_NAME);
    verify(configurationHelper).getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_JOB_TITLE);
    verify(configurationHelper).getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_EMAIL_ADDRESS);
    verify(configurationHelper).getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_TELEPHONE_NUMBER);
    verify(ldapOperations)
        .search(any(LdapTemplate.class), any(LdapQuery.class), any(SubjectMatterExpertDaoImpl.SubjectMatterExpertContactDetailsMapper.class));
    verifyNoMoreInteractionsHelper();
}
 
Example #21
Source File: LdapOperationsImpl.java    From herd with Apache License 2.0 4 votes vote down vote up
@Override
public <T> List<T> search(LdapTemplate ldapTemplate, LdapQuery query, AttributesMapper<T> mapper)
{
    return ldapTemplate.search(query, mapper);
}
 
Example #22
Source File: SubjectMatterExpertDaoImpl.java    From herd with Apache License 2.0 4 votes vote down vote up
@Override
public SubjectMatterExpertContactDetails getSubjectMatterExpertByKey(SubjectMatterExpertKey subjectMatterExpertKey)
{
    // Get LDAP specific configuration settings.
    final String ldapUrl = configurationHelper.getProperty(ConfigurationValue.LDAP_URL);
    final String ldapBase = configurationHelper.getProperty(ConfigurationValue.LDAP_BASE);
    final String ldapUserDn = configurationHelper.getProperty(ConfigurationValue.LDAP_USER_DN);
    final String credStashEncryptionContext = configurationHelper.getProperty(ConfigurationValue.CREDSTASH_HERD_ENCRYPTION_CONTEXT);
    final String ldapUserCredentialName = configurationHelper.getProperty(ConfigurationValue.LDAP_USER_CREDENTIAL_NAME);

    // Log configuration values being used to create LDAP context source.
    LOGGER.info("Creating LDAP context source using the following parameters: {}=\"{}\" {}=\"{}\" {}=\"{}\" {}=\"{}\" {}=\"{}\"...",
        ConfigurationValue.LDAP_URL.getKey(), ldapUrl, ConfigurationValue.LDAP_BASE.getKey(), ldapBase, ConfigurationValue.LDAP_USER_DN.getKey(),
        ldapUserDn, ConfigurationValue.CREDSTASH_HERD_ENCRYPTION_CONTEXT.getKey(), credStashEncryptionContext,
        ConfigurationValue.LDAP_USER_CREDENTIAL_NAME.getKey(), ldapUserCredentialName);

    // Retrieve LDAP user password from the credstash.
    String ldapUserPassword;
    try
    {
        ldapUserPassword = credStashHelper.getCredentialFromCredStash(credStashEncryptionContext, ldapUserCredentialName);
    }
    catch (CredStashGetCredentialFailedException e)
    {
        throw new IllegalStateException(e);
    }

    // Create and initialize an LDAP context source.
    LdapContextSource contextSource = new LdapContextSource();
    contextSource.setUrl(ldapUrl);
    contextSource.setBase(ldapBase);
    contextSource.setUserDn(ldapUserDn);
    contextSource.setPassword(ldapUserPassword);
    contextSource.afterPropertiesSet();

    // Create an LDAP template.
    LdapTemplate ldapTemplate = new LdapTemplate(contextSource);

    // Create an LDAP query.
    LdapQuery ldapQuery = query().where(configurationHelper.getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_ID)).is(subjectMatterExpertKey.getUserId());

    // Create a subject matter expert contact details mapper.
    SubjectMatterExpertContactDetailsMapper subjectMatterExpertContactDetailsMapper =
        new SubjectMatterExpertContactDetailsMapper(configurationHelper.getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_FULL_NAME),
            configurationHelper.getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_JOB_TITLE),
            configurationHelper.getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_EMAIL_ADDRESS),
            configurationHelper.getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_TELEPHONE_NUMBER));

    // Gets information for the specified subject matter expert.
    List<SubjectMatterExpertContactDetails> subjectMatterExpertContactDetailsList =
        ldapOperations.search(ldapTemplate, ldapQuery, subjectMatterExpertContactDetailsMapper);

    // Return the results.
    return CollectionUtils.isNotEmpty(subjectMatterExpertContactDetailsList) ? subjectMatterExpertContactDetailsList.get(0) : null;
}
 
Example #23
Source File: OdmManagerImpl.java    From spring-ldap with Apache License 2.0 4 votes vote down vote up
@Override
public <T> List<T> search(Class<T> clazz, LdapQuery query) {
    return ldapTemplate.find(query, clazz);
}
 
Example #24
Source File: LdapOperations.java    From spring-ldap with Apache License 2.0 2 votes vote down vote up
/**
 * Utility method to perform a simple LDAP 'bind' authentication. Search for
 * the LDAP entry to authenticate using the supplied LdapQuery; use
 * the DN of the found entry together with the password as input to
 * {@link ContextSource#getContext(String, String)}, thus authenticating the
 * entry.
 * <p>
 *     <b>Note:</b> This method differs from the older authenticate methods in that encountered
 *     exceptions are thrown rather than supplied to a callback for handling.
 * </p>
 *
 * @param query the LdapQuery specifying the details of the search.
 * @param password the password to use for authentication.
 * @param mapper the callback that will be called to perform operations
 * on the DirContext authenticated with the found user.
 * <code>false</code> otherwise.
 * @return the result from the callback.
 * @throws IncorrectResultSizeDataAccessException if more than one users were found
 * @throws org.springframework.dao.EmptyResultDataAccessException if only one user was found
 * @throws NamingException if something went wrong in authentication.
 *
 * @since 2.0
 * @see org.springframework.ldap.query.LdapQueryBuilder
 */
<T> T authenticate(LdapQuery query, String password, AuthenticatedLdapEntryContextMapper<T> mapper);
 
Example #25
Source File: LdapOperations.java    From spring-ldap with Apache License 2.0 2 votes vote down vote up
/**
 * Search for objects in the directory tree matching the specified LdapQuery, expecting to find exactly one match.
 * The referenced class must have object-directory mapping metadata specified using
 * {@link org.springframework.ldap.odm.annotations.Entry} and associated annotations.
 * @param query the LDAP query specification
 * @param clazz The Java type to return
 * @param <T> The Java type to return
 * @return The single entry matching the search specification.
 * @since 2.0
 * @throws org.springframework.ldap.NamingException on LDAP error.
 * @throws org.springframework.dao.EmptyResultDataAccessException if no matching entry can be found
 * @throws IncorrectResultSizeDataAccessException if more than one matching entry is found
 */
<T> T findOne(LdapQuery query, Class<T> clazz);
 
Example #26
Source File: LdapOperations.java    From spring-ldap with Apache License 2.0 2 votes vote down vote up
/**
 * Search for entries in the LDAP directory. The referenced class must have object-directory
 * mapping metadata specified using {@link org.springframework.ldap.odm.annotations.Entry} and associated annotations.
 * <p>
 * Only those entries that both match the query search filter and
 * are represented by the given Java class are returned.
 *
 * @param <T> The Java type to return
 * @param query the LDAP query specification
 * @param clazz The Java type to return
 * @return All matching entries.
 *
 * @throws org.springframework.ldap.NamingException on error.
 * @see org.springframework.ldap.query.LdapQueryBuilder
 * @since 2.0
 */
<T> List<T> find(LdapQuery query, Class<T> clazz);
 
Example #27
Source File: LdapOperations.java    From spring-ldap with Apache License 2.0 2 votes vote down vote up
/**
 * Perform a search for a unique entry matching the specified LDAP
 * query and return the found object. If no entry is found or if there
 * are more than one matching entry, an
 * {@link IncorrectResultSizeDataAccessException} is thrown.
 * @param query the LDAP query specification.
 * @return the single object returned by the mapper that matches the search
 * criteria.
 * @throws IncorrectResultSizeDataAccessException if the result is not one unique entry
 * @since 2.0
 * @see org.springframework.ldap.query.LdapQueryBuilder
 */
<T> T searchForObject(LdapQuery query, ContextMapper<T> mapper);
 
Example #28
Source File: LdapOperations.java    From spring-ldap with Apache License 2.0 2 votes vote down vote up
/**
 * Perform a search for a unique entry matching the specified LDAP
 * query and return the found entry as a DirContextOperation instance. If no entry is found or if there
 * are more than one matching entry, an
 * {@link IncorrectResultSizeDataAccessException} is thrown.
 * @param query the LDAP query specification.
 * @return the single entry matching the query as a DirContextOperations instance.
 * @throws IncorrectResultSizeDataAccessException if the result is not one unique entry
 * @since 2.0
 * @see org.springframework.ldap.query.LdapQueryBuilder
 */
DirContextOperations searchForContext(LdapQuery query);
 
Example #29
Source File: LdapOperations.java    From spring-ldap with Apache License 2.0 2 votes vote down vote up
/**
 * Perform a search with parameters from the specified LdapQuery. The Attributes of the found entries will be
 * supplied to the <code>AttributesMapper</code> for processing, and all
 * returned objects will be collected in a list to be returned.
 *
 * @param query the LDAP query specification.
 * @param mapper the <code>Attributes</code> to supply all found Attributes to.
 * @return a <code>List</code> containing all entries received from the
 * <code>Attributes</code>.
 *
 * @throws NamingException if any error occurs.
 * @since 2.0
 * @see org.springframework.ldap.query.LdapQueryBuilder
 */
<T> List<T> search(LdapQuery query, AttributesMapper<T> mapper);
 
Example #30
Source File: LdapOperations.java    From spring-ldap with Apache License 2.0 2 votes vote down vote up
/**
 * Perform a search with parameters from the specified LdapQuery. All found objects will be supplied to the
 * <code>ContextMapper</code> for processing, and all returned objects will be collected in a list to be returned.
 *
 * @param query the LDAP query specification.
 * @param mapper the <code>ContextMapper</code> to supply all found entries to.
 * @return a <code>List</code> containing all entries received from the
 * <code>ContextMapper</code>.
 *
 * @throws NamingException if any error occurs.
 * @since 2.0
 * @see org.springframework.ldap.query.LdapQueryBuilder
 */
<T> List<T> search(LdapQuery query, ContextMapper<T> mapper);