org.springframework.ldap.core.DistinguishedName Java Examples

The following examples show how to use org.springframework.ldap.core.DistinguishedName. 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: LdapService.java    From ctsms with GNU Lesser General Public License v2.1 6 votes vote down vote up
private AttributesMapper getAttributeMapper(final Object... baseArgs) {
	return new AttributesMapper() {

		@Override
		public Object mapFromAttributes(Attributes attrs) throws NamingException {
			LdapEntryVO entry = new LdapEntryVO();
			entry.setUsername((String) attrs.get(USERNAME_ATTRIBUTE_ID).get());
			DistinguishedName dn = new DistinguishedName(getBase(baseArgs));
			dn.add(USERNAME_ATTRIBUTE_ID, entry.getUsername());
			entry.setAbsoluteDn(dn.encode());
			Map<String, Object> attributes = new LinkedHashMap<String, Object>();
			if (searchResultAttributes != null) {
				for (int i = 0; i < searchResultAttributes.length; i++) {
					Attribute attr = attrs.get(searchResultAttributes[i]);
					if (attr != null) {
						attributes.put(searchResultAttributes[i], attr.get());
					}
				}
			}
			entry.setAttributes(attributes);
			return entry;
		}
	};
}
 
Example #2
Source File: DummyDaoLdapAndHibernateImpl.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
public void create(OrgPerson person) {
	DistinguishedName dn = new DistinguishedName();
       dn.add("ou", person.getCountry());
       dn.add("ou", person.getCompany());
       dn.add("cn", person.getFullname());

       DirContextAdapter ctx = new DirContextAdapter();
       ctx.setAttributeValues("objectclass", new String[] { "top", "person" });
       ctx.setAttributeValue("cn", person.getFullname());
       ctx.setAttributeValue("sn", person.getLastname());
       ctx.setAttributeValue("description", person.getDescription());
       ldapTemplate.bind(dn, ctx, null);
	this.getHibernateTemplate().saveOrUpdate(person);


}
 
Example #3
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 #4
Source File: DnParsePerformanceITest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateFromString() {
	StopWatch stopWatch = new StopWatch("Create from String");
	stopWatch.start();

	for (int i = 0; i < 2000; i++) {
		DistinguishedName migpath = new DistinguishedName("OU=G,OU=I,OU=M");
		DistinguishedName path1 = new DistinguishedName("cn=john.doe, OU=Users,OU=SE,OU=G,OU=I,OU=M");
		DistinguishedName path2 = new DistinguishedName("cn=john.doe, OU=Users,OU=SE,ou=G,OU=i,OU=M, ou=foo");
		DistinguishedName path3 = new DistinguishedName("ou=G,OU=i,OU=M, ou=foo");
		DistinguishedName path4 = new DistinguishedName("ou=G,OU=i,ou=m");

		DistinguishedName pathE1 = new DistinguishedName("cn=john.doe, OU=Users,OU=SE,ou=G,OU=L,OU=M, ou=foo");
		DistinguishedName pathE2 = new DistinguishedName("cn=john.doe, OU=Users,OU=SE");
	}

	stopWatch.stop();
	System.out.println(stopWatch.prettyPrint());
}
 
Example #5
Source File: IncrementalAttributeMapperITest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
private void createUser(String username) throws UnsupportedEncodingException {
    DirContextAdapter ctx = new DirContextAdapter(new DistinguishedName(OU_DN).append("cn", username));

    ctx.addAttributeValue("objectclass", "top");
    ctx.addAttributeValue("objectclass", "person");
    ctx.addAttributeValue("objectclass", "organizationalPerson");
    ctx.addAttributeValue("objectclass", "user");

    ctx.setAttributeValue("givenName", username);
    ctx.setAttributeValue("userPrincipalName", username + "@example.com");
    ctx.setAttributeValue("cn", username);
    ctx.setAttributeValue("description", "Dummy user");
    ctx.setAttributeValue("sAMAccountName", username.toUpperCase() + "." + username.toUpperCase());
    ctx.setAttributeValue("userAccountControl", "512");

    String newQuotedPassword = "\"" + DEFAULT_PASSWORD + "\"";
    ctx.setAttributeValue("unicodePwd", newQuotedPassword.getBytes("UTF-16LE"));

    ldapTemplate.bind(ctx);
}
 
Example #6
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 #7
Source File: BaseLdapPathBeanPostProcessorTest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@Test
public void testPostProcessBeforeInitializationWithLdapPathAwareNoBasePathSet() throws Exception {
	final LdapContextSource expectedContextSource = new LdapContextSource();
	String expectedPath = "dc=example, dc=com";
	expectedContextSource.setBase(expectedPath);

	tested = new BaseLdapPathBeanPostProcessor() {
		BaseLdapPathSource getBaseLdapPathSourceFromApplicationContext() {
			return expectedContextSource;
		}
	};

	Object result = tested.postProcessBeforeInitialization(ldapPathAwareMock, "someName");

       verify(ldapPathAwareMock).setBaseLdapPath(new DistinguishedName(expectedPath));

	assertThat(result).isSameAs(ldapPathAwareMock);
}
 
Example #8
Source File: LdapTemplateLookupOpenLdapITest.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
public void testLookup_AttributesMapper_DistinguishedName() {
    AttributesMapper mapper = new PersonAttributesMapper();
    Person person = (Person) tested.lookup(new DistinguishedName(
            "cn=Some Person2, ou=company1,c=Sweden"), mapper);

    assertThat(person.getFullname()).isEqualTo("Some Person2");
    assertThat(person.getLastname()).isEqualTo("Person2");
    assertThat(person.getDescription()).isEqualTo("Sweden, Company1, Some Person2");
}
 
Example #9
Source File: IncrementalAttributeMapperITest.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
@Test
public void verifyRetrievalOfLotsOfAttributeValues() {
    DistinguishedName testgroupDn = new DistinguishedName(OU_DN).append("cn", "testgroup");

    // The 'member' attribute consists of > 1500 entries and will not be returned without range specifier.
    DirContextOperations ctx = ldapTemplate.lookupContext(testgroupDn);
    assertThat(ctx.getStringAttribute("member")).isNull();

    DefaultIncrementalAttributesMapper attributeMapper = new DefaultIncrementalAttributesMapper(new String[]{"member", "cn"});
    assertThat(attributeMapper.hasMore()).as("There should be more results to get").isTrue();

    String[] attributesArray = attributeMapper.getAttributesForLookup();
    assertThat(attributesArray.length).isEqualTo(2);
    assertThat(attributesArray[0]).isEqualTo("member");
    assertThat(attributesArray[1]).isEqualTo("cn");

    // First iteration - there should now be more members left, but all cn values should have been collected.
    ldapTemplate.lookup(testgroupDn, attributesArray, attributeMapper);

    assertThat(attributeMapper.hasMore()).as("There should be more results to get").isTrue();
    // Only member attribute should be requested in this query.
    attributesArray = attributeMapper.getAttributesForLookup();
    assertThat(attributesArray.length).isEqualTo(1);
    assertThat(attributesArray[0]).isEqualTo("member;Range=1500-*");

    // Second iteration - all data should now have been collected.
    ldapTemplate.lookup(testgroupDn, attributeMapper.getAttributesForLookup(), attributeMapper);
    assertThat(attributeMapper.hasMore()).as("There should be no more results to get").isFalse();

    List memberValues = attributeMapper.getValues("member");
    assertThat(memberValues).isNotNull();
    assertThat(memberValues).hasSize(1501);

    List cnValues = attributeMapper.getValues("cn");
    assertThat(cnValues).isNotNull();
    assertThat(cnValues).hasSize(1);
}
 
Example #10
Source File: LdapTemplateLookupOpenLdapITest.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies that only the subset is used when specifying a subset of the
 * available attributes as return attributes. Uses DistinguishedName instead
 * of plain string as name.
 */
public void testLookup_ReturnAttributes_AttributesMapper_DistinguishedName() {
    AttributesMapper mapper = new SubsetPersonAttributesMapper();
    Person person = (Person) tested.lookup(new DistinguishedName(
            "cn=Some Person2, ou=company1,c=Sweden"),
            new String[] { "cn" }, mapper);

    assertThat(person.getFullname()).isEqualTo("Some Person2");
    assertThat(person.getLastname()).as("lastName should not be set").isNull();
    assertThat(person.getDescription()).as("description should not be set").isNull();
}
 
Example #11
Source File: BaseLdapPathBeanPostProcessorTest.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
@Test
public void testPostProcessBeforeInitializationWithLdapPathAwareBasePathSet() throws Exception {
	String expectedPath = "dc=example, dc=com";
	tested.setBasePath(new DistinguishedName(expectedPath));

	Object result = tested.postProcessBeforeInitialization(ldapPathAwareMock, "someName");

	verify(ldapPathAwareMock).setBaseLdapPath(new DistinguishedName(expectedPath));

	assertThat(result).isSameAs(ldapPathAwareMock);
}
 
Example #12
Source File: BaseLdapPathBeanPostprocessorNamespaceConfigITest.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
@Test
public void testPostProcessBeforeInitializationWithNamespaceConfigAndPooling() throws Exception {
    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
            "/conf/baseLdapPathPostProcessorPoolingNamespaceTestContext.xml");
    DummyBaseLdapPathAware tested = ctx.getBean(DummyBaseLdapPathAware.class);

    DistinguishedName base = tested.getBase();
    assertThat(base).isNotNull();
    assertThat(base).isEqualTo(new DistinguishedName("dc=jayway,dc=se"));

    DummyBaseLdapNameAware otherTested = ctx.getBean(DummyBaseLdapNameAware.class);
    assertThat(otherTested.getBaseLdapPath()).isEqualTo(LdapUtils.newLdapName("dc=jayway,dc=se"));
}
 
Example #13
Source File: BaseLdapPathBeanPostprocessorNamespaceConfigITest.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
@Test
public void testPostProcessBeforeInitializationWithNamespaceConfig() throws Exception {
	ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
               "/conf/baseLdapPathPostProcessorNamespaceTestContext.xml");
	DummyBaseLdapPathAware tested = ctx.getBean(DummyBaseLdapPathAware.class);

	DistinguishedName base = tested.getBase();
	assertThat(base).isNotNull();
	assertThat(base).isEqualTo(new DistinguishedName("dc=jayway,dc=se"));

       DummyBaseLdapNameAware otherTested = ctx.getBean(DummyBaseLdapNameAware.class);
       assertThat(otherTested.getBaseLdapPath()).isEqualTo(LdapUtils.newLdapName("dc=jayway,dc=se"));
   }
 
Example #14
Source File: BaseLdapPathBeanPostprocessorITest.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
@Test
public void testPostProcessBeforeInitializationTransactionProxy() throws Exception {
	ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
               "/conf/baseLdapPathPostProcessorTransactionTestContext.xml");
	DummyBaseLdapPathAware tested = (DummyBaseLdapPathAware) ctx.getBean("dummyBaseContextAware");

	DistinguishedName base = tested.getBase();
	assertThat(base).isNotNull();
	assertThat(base).isEqualTo(new DistinguishedName("dc=261consulting,dc=com"));
}
 
Example #15
Source File: BaseLdapPathBeanPostprocessorITest.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
@Test
public void testPostProcessBeforeInitializationBaseSetInProperty() throws Exception {
	ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
               "/conf/baseLdapPathPostProcessorPropertyOverrideTestContext.xml");
	DummyBaseLdapPathAware tested = (DummyBaseLdapPathAware) ctx.getBean("dummyBaseContextAware");

	DistinguishedName base = tested.getBase();
	assertThat(base).isNotNull();
	assertThat(base).isEqualTo(new DistinguishedName("cn=john doe"));
}
 
Example #16
Source File: BaseLdapPathBeanPostprocessorITest.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
@Test
public void testPostProcessBeforeInitializationMultipleContextSourcesOneSpecified() throws Exception {
	ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
               "/conf/baseLdapPathPostProcessorMultiContextSourceOneSpecTestContext.xml");
	DummyBaseLdapPathAware tested = (DummyBaseLdapPathAware) ctx.getBean("dummyBaseContextAware");

	DistinguishedName base = tested.getBase();
	assertThat(base).isNotNull();
	assertThat(base).isEqualTo(new DistinguishedName("cn=john doe,dc=261consulting,dc=com"));
}
 
Example #17
Source File: BaseLdapPathBeanPostprocessorITest.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
@Test
public void testPostProcessBeforeInitialization() throws Exception {
	ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
               "/conf/baseLdapPathPostProcessorTestContext.xml");
	DummyBaseLdapPathAware tested = ctx.getBean(DummyBaseLdapPathAware.class);

	DistinguishedName base = tested.getBase();
	assertThat(base).isNotNull();
	assertThat(base).isEqualTo(new DistinguishedName("dc=261consulting,dc=com"));

       DummyBaseLdapNameAware otherTested = ctx.getBean(DummyBaseLdapNameAware.class);
       assertThat(otherTested.getBaseLdapPath()).isEqualTo(LdapUtils.newLdapName("dc=261consulting,dc=com"));
   }
 
Example #18
Source File: LdapUserRolesProvider.java    From fiat with Apache License 2.0 5 votes vote down vote up
private String getUserFullDn(String userId) {
  String rootDn = LdapUtils.parseRootDnFromUrl(configProps.getUrl());
  DistinguishedName root = new DistinguishedName(rootDn);
  log.debug("Root DN: " + root.toString());

  String[] formatArgs = new String[] {LdapEncoder.nameEncode(userId)};

  String partialUserDn;
  if (!StringUtils.isEmpty(configProps.getUserSearchFilter())) {
    try {
      DirContextOperations res =
          ldapTemplate.searchForSingleEntry(
              configProps.getUserSearchBase(), configProps.getUserSearchFilter(), formatArgs);
      partialUserDn = res.getDn().toString();
    } catch (IncorrectResultSizeDataAccessException e) {
      log.error("Unable to find a single user entry", e);
      return null;
    }
  } else {
    partialUserDn = configProps.getUserDnPattern().format(formatArgs);
  }

  DistinguishedName user = new DistinguishedName(partialUserDn);
  log.debug("User portion: " + user.toString());

  try {
    Name fullUser = root.addAll(user);
    log.debug("Full user DN: " + fullUser.toString());
    return fullUser.toString();
  } catch (InvalidNameException ine) {
    log.error("Could not assemble full userDn", ine);
  }
  return null;
}
 
Example #19
Source File: LdapAndJdbcDummyDaoImpl.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
public void create(String country, String company, String fullname, String lastname, String description) {
	DistinguishedName dn = new DistinguishedName();
	dn.add("ou", country);
	dn.add("ou", company);
	dn.add("cn", fullname);

	DirContextAdapter ctx = new DirContextAdapter();
	ctx.setAttributeValues("objectclass", new String[] { "top", "person" });
	ctx.setAttributeValue("cn", fullname);
	ctx.setAttributeValue("sn", lastname);
	ctx.setAttributeValue("description", description);
	ldapTemplate.bind(dn, ctx, null);
	jdbcTemplate.update("insert into PERSON values(?, ?, ?)", new Object[] { fullname, lastname, description });
}
 
Example #20
Source File: LdapServiceImplTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Before
public void init() throws UnknownHostException {
    testUser = buildTestUser();
    slcUser = buildSlcUser();
    uid = testUser.getUid();
    group = buildTestGroup();

    ldapTemplate = Mockito.mock(LdapTemplate.class);

    DistinguishedName dn = new DistinguishedName("ou=LocalNew");
    String[] attributes = new String[] {"*", LdapService.CREATE_TIMESTAMP, LdapService.MODIFY_TIMESTAMP };

    // mock: ldapTemplate.search(dn, filter.toString(), SearchControls.SUBTREE_SCOPE, new String[] {"*", CREATE_TIMESTAMP, MODIFY_TIMESTAMP }, new UserContextMapper())
    Mockito.when(ldapTemplate.search(
            Mockito.eq(dn),
            Mockito.eq("(&(objectclass=person)(uid=slcoperator))"),
            Mockito.eq(SearchControls.SUBTREE_SCOPE),
            Mockito.eq(attributes),
            Mockito.any(UserContextMapper.class))).thenReturn(Arrays.asList(slcUser));

    // mock: ldapTemplate.searchForObject(dn, filter.toString(), new GroupContextMapper());
    Mockito.when(ldapTemplate.searchForObject(
            Mockito.eq(dn),
            Mockito.eq("(&(objectclass=posixGroup)(cn=SLC Operator))"),
            Mockito.any(GroupContextMapper.class)))
        .thenReturn(group);

    // mock: ldapTemplate.search(dn, filter.toString(), new GroupContextMapper()
    Mockito.when(ldapTemplate.search(
            Mockito.eq(dn),
            Mockito.eq("(&(objectclass=posixGroup)(memberuid=slcoperator))"),
            Mockito.any(GroupContextMapper.class)))
        .thenReturn(Arrays.asList(group));

    ldapService.setLdapTemplate(ldapTemplate);
}
 
Example #21
Source File: LdapDummyDaoImpl.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
public void create(String country, String company, String fullname,
        String lastname, String description) {
    DistinguishedName dn = new DistinguishedName();
    dn.add("ou", country);
    dn.add("ou", company);
    dn.add("cn", fullname);

    DirContextAdapter ctx = new DirContextAdapter();
    ctx.setAttributeValues("objectclass", new String[] { "top", "person" });
    ctx.setAttributeValue("cn", fullname);
    ctx.setAttributeValue("sn", lastname);
    ctx.setAttributeValue("description", description);
    ldapTemplate.bind(dn, ctx, null);
}
 
Example #22
Source File: ActiveDirectoryLdapAuthoritiesPopulator.java    From maven-framework-project with MIT License 5 votes vote down vote up
@Override
public Collection<? extends GrantedAuthority> getGrantedAuthorities(DirContextOperations userData, String username) {
    String[] groups = userData.getStringAttributes("memberOf");
    List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

    for (String group : groups) {
        LdapRdn authority = new DistinguishedName(group).removeLast();
        authorities.add(new SimpleGrantedAuthority(authority.getValue()));
    }
    return authorities;
}
 
Example #23
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 #24
Source File: UsersTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Test
public void testAuthenticate() throws AuthenticationException {
    DistinguishedName dn = new DistinguishedName("ou=SLIAdmin");
    Mockito.when(
            ldapTemplate.authenticate(Mockito.eq(dn), Mockito.eq("(&(objectclass=person)(uid=testuser))"),
                    Mockito.eq("testuser1234"), Mockito.any(AuthenticationErrorCallback.class))).thenReturn(true);
    User mockUser = new User();
    Map<String, String> attributes = new HashMap<String, String>();
    attributes.put("userName", "Test User");
    mockUser.attributes = attributes;
    mockUser.userId = "testuser";
    Mockito.when(
            ldapTemplate.searchForObject(Mockito.eq(dn), Mockito.eq("(&(objectclass=person)(uid=testuser))"),
                    Mockito.any(ContextMapper.class))).thenReturn(mockUser);
    List<String> mockGroups = new ArrayList<String>();
    mockGroups.add("TestGroup1");
    mockGroups.add("TestGroup2");
    Mockito.when(
            ldapTemplate.search(Mockito.eq(dn), Mockito.eq("(&(objectclass=posixGroup)(memberuid=testuser))"),
                    Mockito.any(GroupContextMapper.class))).thenReturn(mockGroups);

    UserService.User user = userService.authenticate("SLIAdmin", "testuser", "testuser1234");
    assertEquals("testuser", user.getUserId());
    assertEquals("Test User", user.getAttributes().get("userName"));
    assertEquals("staff", user.getAttributes().get("userType"));
    assertEquals(2, user.getRoles().size());
    assertEquals("TestGroup1", user.getRoles().get(0));
    assertEquals("TestGroup2", user.getRoles().get(1));
}
 
Example #25
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 #26
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 #27
Source File: UsersTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Test
public void testSandboxAuthenticate() throws AuthenticationException {
    DistinguishedName dn = new DistinguishedName("ou=SLIAdmin");
    Mockito.when(
            ldapTemplate.authenticate(Mockito.eq(dn), Mockito.eq("(&(objectclass=person)(uid=testuser))"),
                    Mockito.eq("testuser1234"), Mockito.any(AuthenticationErrorCallback.class))).thenReturn(true);
    User mockUser = new User();
    Map<String, String> attributes = new HashMap<String, String>();
    attributes.put("userName", "Test User");
    attributes.put("Tenant", "mytenant");
    attributes.put("isAdmin", "true");
    mockUser.attributes = attributes;
    mockUser.userId = "testuser";
    Mockito.when(
            ldapTemplate.searchForObject(Mockito.eq(dn), Mockito.eq("(&(objectclass=person)(uid=testuser))"),
                    Mockito.any(ContextMapper.class))).thenReturn(mockUser);
    List<String> mockGroups = new ArrayList<String>();
    mockGroups.add("TestGroup1");
    mockGroups.add("TestGroup2");
    Mockito.when(
            ldapTemplate.search(Mockito.eq(dn), Mockito.eq("(&(objectclass=posixGroup)(memberuid=testuser))"),
                    Mockito.any(GroupContextMapper.class))).thenReturn(mockGroups);

    UserService.User user = userService.authenticate("SLIAdmin", "testuser", "testuser1234");
    assertEquals("testuser", user.getUserId());
    assertEquals("Test User", user.getAttributes().get("userName"));
    assertEquals("mytenant", user.getAttributes().get("Tenant"));
    assertEquals("admin", user.getAttributes().get("userType"));
    assertEquals(2, user.getRoles().size());
    assertEquals("TestGroup1", user.getRoles().get(0));
    assertEquals("TestGroup2", user.getRoles().get(1));
}
 
Example #28
Source File: UsersTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Test
public void testStudentAuthenticate() throws AuthenticationException {
    DistinguishedName dn = new DistinguishedName("ou=Students");
    List<String> mockGroups = new ArrayList<String>();
    mockGroups.add("Student");
    Mockito.when(
            ldapTemplate.search(Mockito.eq(dn), Mockito.eq("(&(objectclass=posixGroup)(memberuid=studentuser))"),
                    Mockito.any(GroupContextMapper.class))).thenReturn(mockGroups);

    Mockito.when(
            ldapTemplate.authenticate(Mockito.eq(dn), Mockito.eq("(&(objectclass=person)(uid=studentuser))"),
                    Mockito.eq("studentuser1234"), Mockito.any(AuthenticationErrorCallback.class))).thenReturn(true);

    Map<String, String> attributes = new HashMap<String, String>();
    attributes.put("userName", "Student User");
    attributes.put("userType", "student");
    attributes.put("employeeNumber", "1234567890");
    User mockUser = new User("studentuser", mockGroups, attributes);

    Mockito.when(
            ldapTemplate.searchForObject(Mockito.eq(dn), Mockito.eq("(&(objectclass=person)(uid=studentuser))"),
                    Mockito.any(ContextMapper.class))).thenReturn(mockUser);

    UserService.User user = userService.authenticate("Students", "studentuser", "studentuser1234");
    assertEquals("1234567890", user.getUserId());
    assertEquals("Student User", user.getAttributes().get("userName"));
    assertEquals("student", user.getAttributes().get("userType"));
    assertEquals(1, user.getRoles().size());
    assertEquals("Student", user.getRoles().get(0));
}
 
Example #29
Source File: UsersTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Test
public void testStaffAuthenticate() throws AuthenticationException {
    DistinguishedName dn = new DistinguishedName("ou=StaffMember");
    List<String> mockGroups = new ArrayList<String>();
    mockGroups.add("Educator");
    Mockito.when(
            ldapTemplate.search(Mockito.eq(dn), Mockito.eq("(&(objectclass=posixGroup)(memberuid=staffuser))"),
                    Mockito.any(GroupContextMapper.class))).thenReturn(mockGroups);

    Mockito.when(
            ldapTemplate.authenticate(Mockito.eq(dn), Mockito.eq("(&(objectclass=person)(uid=staffuser))"),
                    Mockito.eq("staffuser1234"), Mockito.any(AuthenticationErrorCallback.class))).thenReturn(true);

    Map<String, String> attributes = new HashMap<String, String>();
    attributes.put("userName", "Staff User");
    attributes.put("userType", "staff");
    User mockUser = new User("staffuser", mockGroups, attributes);

    Mockito.when(
            ldapTemplate.searchForObject(Mockito.eq(dn), Mockito.eq("(&(objectclass=person)(uid=staffuser))"),
                    Mockito.any(ContextMapper.class))).thenReturn(mockUser);

    UserService.User user = userService.authenticate("StaffMember", "staffuser", "staffuser1234");
    assertEquals("staffuser", user.getUserId());
    assertEquals("Staff User", user.getAttributes().get("userName"));
    assertEquals("staff", user.getAttributes().get("userType"));
    assertEquals(1, user.getRoles().size());
    assertEquals("Educator", user.getRoles().get(0));
}
 
Example #30
Source File: LdapPrincipalDaoImpl.java    From rice with Educational Community License v2.0 4 votes vote down vote up
public <T> List<T> search(Class<T> type, Map<String, Object> criteria) {
    AndFilter filter = new AndFilter();
    
    for (Map.Entry<String, Object> entry : criteria.entrySet()) {
        //attempting to handle null values to prevent NPEs in this code.
        if (entry.getValue() == null) {
            entry.setValue("null");
        }
        if (entry.getValue() instanceof Iterable) {
            OrFilter orFilter = new OrFilter();
            for (String value : (Iterable<String>) entry.getValue()) {
                if (value.startsWith("!")) {
                    orFilter.or(new NotFilter(new LikeFilter(entry.getKey(), value.substring(1))));
                } else {
                    orFilter.or(new LikeFilter(entry.getKey(), value));
                }
            }
            filter.and(orFilter);
        }
        else {
            if (((String)entry.getValue()).startsWith("!")) {
                filter.and(new NotFilter(new LikeFilter(entry.getKey(), ((String)entry.getValue()).substring(1))));
            } else {
                filter.and(new LikeFilter(entry.getKey(), (String) entry.getValue()));
            }
        }
    };
    
    info("Using filter ", filter);

    debug("Looking up mapper for ", type.getSimpleName());
    final ContextMapper customMapper = contextMappers.get(type.getSimpleName());

    ContextMapperCallbackHandler callbackHandler = new CustomContextMapperCallbackHandler(customMapper);
    
    try {
        getLdapTemplate().search(DistinguishedName.EMPTY_PATH, 
                                 filter.encode(), 
                                 getSearchControls(), callbackHandler);
    }
    catch (SizeLimitExceededException e) {
        // Ignore this. We want to limit our results.
    }

    return callbackHandler.getList();
}