org.springframework.ldap.support.LdapNameBuilder Java Examples

The following examples show how to use org.springframework.ldap.support.LdapNameBuilder. 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: SpringLdapController.java    From Spring-5.0-Projects with MIT License 6 votes vote down vote up
/**
 * This method can be used to add new user by passing required parameters.
 */
private void addUser() {
	LdapAuthUser ldapUser = new LdapAuthUser();
       ldapUser.setUserName("kpatel");
       ldapUser.setPassword("test1234");
       ldapUser.setFirstName("Komal");
       ldapUser.setSurName("Patel");
       ldapUser.setIsNew(true);
       
       Name dn = LdapNameBuilder.newInstance()
             .add("ou=users")
             .add("uid=kpatel")
             .build();
       ldapUser.setId(dn);
       
       ldapAuthService.addUser(ldapUser);
}
 
Example #2
Source File: LdapAuthRepositoryCustomImpl.java    From Spring-5.0-Projects with MIT License 6 votes vote down vote up
@Override
public void createByBindOperation(LdapAuthUser ldapAuthUser) {
	
	DirContextOperations ctx = new DirContextAdapter();
	ctx.setAttributeValues("objectclass", new String[] {"top", "person", "organizationalPerson","inetOrgPerson"});
	ctx.setAttributeValue("cn", ldapAuthUser.getFirstName());
	ctx.setAttributeValue("sn", ldapAuthUser.getSurName());
	ctx.setAttributeValue("uid", ldapAuthUser.getUserName());
	ctx.setAttributeValue("userPassword", ldapAuthUser.getPassword());
	
	Name dn = LdapNameBuilder.newInstance()
		      .add("ou=users")
		      .add("uid=bpatel")
		      .build();
	
	ctx.setDn(dn);
	ldapTemplate.bind(ctx);
	
}
 
Example #3
Source File: KnoxSSOAuthenticationFilter.java    From metron with Apache License 2.0 6 votes vote down vote up
/**
 * Builds the Spring Authentication object using the supplied user name and groups looked up from LDAP.  Groups are currently
 * mapped directly to Spring roles by converting to upper case and prepending the name with "ROLE_".
 * @param userName The username to build the Authentication object with.
 * @param httpRequest HttpServletRequest
 * @return Authentication object for the given user.
 */
protected Authentication getAuthentication(String userName, HttpServletRequest httpRequest) {
  String ldapName = LdapNameBuilder.newInstance().add(userSearchBase).add("uid", userName).build().toString();

  // Search ldap for a user's groups and convert to a Spring role
  List<GrantedAuthority> grantedAuths = ldapTemplate.search(query()
          .where("objectclass")
          .is("groupOfNames")
          .and("member")
          .is(ldapName), (AttributesMapper<String>) attrs -> (String) attrs.get("cn").get())
          .stream()
          .map(group -> String.format("%s%s", SECURITY_ROLE_PREFIX, group.toUpperCase()))
          .map(SimpleGrantedAuthority::new).collect(Collectors.toList());

  final UserDetails principal = new User(userName, "", grantedAuths);
  final UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
          principal, "", grantedAuths);
  WebAuthenticationDetails webDetails = new WebAuthenticationDetails(httpRequest);
  authentication.setDetails(webDetails);
  return authentication;
}
 
Example #4
Source File: LdapTemplateOdmWithNoDnAnnotationsITest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreate() {
    Person person = new Person();
    person.setDn(LdapNameBuilder.newInstance("ou=company1,ou=Sweden")
            .add("cn", "New Person").build());
    person.setCommonName("New Person");
    person.setSurname("Person");
    person.setDesc(Arrays.asList("This is the description"));
    person.setTelephoneNumber("0123456");

    tested.create(person);

    assertThat(tested.findAll(Person.class)).hasSize(6);

    person = tested.findOne(query()
            .where("cn").is("New Person"), Person.class);

    assertThat(person.getCommonName()).isEqualTo("New Person");
    assertThat(person.getSurname()).isEqualTo("Person");
    assertThat(person.getDesc().get(0)).isEqualTo("This is the description");
    assertThat(person.getTelephoneNumber()).isEqualTo("0123456");
    assertThat(person.getEntryUuid()).describedAs("The operational attribute 'entryUUID' was not set").isNotEmpty();
}
 
Example #5
Source File: DefaultObjectDirectoryMapper.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@Override
public Name getCalculatedId(Object entry) {
    Assert.notNull(entry, "Entry must not be null");
    EntityData entityData = getEntityData(entry.getClass());
    if(entityData.metaData.canCalculateDn()) {
        Set<AttributeMetaData> dnAttributes = entityData.metaData.getDnAttributes();
        LdapNameBuilder ldapNameBuilder = LdapNameBuilder.newInstance(entityData.metaData.getBase());

        for (AttributeMetaData dnAttribute : dnAttributes) {
            Object dnFieldValue = ReflectionUtils.getField(dnAttribute.getField(), entry);
            if(dnFieldValue == null) {
                throw new IllegalStateException(
                        String.format("DnAttribute for field %s on class %s is null; cannot build DN",
                                dnAttribute.getField().getName(), entry.getClass().getName()));
            }

            ldapNameBuilder.add(dnAttribute.getDnAttribute().value(), dnFieldValue.toString());
        }

        return ldapNameBuilder.build();
    }

    return null;
}
 
Example #6
Source File: LdapAuthRepositoryCustomImpl.java    From Spring-5.0-Projects with MIT License 5 votes vote down vote up
@Override
public void deleteFromTemplateWithUnbind(String userName) {
	Name dn = LdapNameBuilder.newInstance()
		      .add("ou=users")
		      .add("uid="+userName)
		      .build();
	ldapTemplate.unbind(dn);
}
 
Example #7
Source File: LdapAuthService.java    From Spring-5.0-Projects with MIT License 5 votes vote down vote up
public void addUser(LdapAuthUser ldapAuthUser) {
	Name dn = LdapNameBuilder
		      .newInstance()
		      .add("uid", ldapAuthUser.getUserName())
		      .add("ou", "users")
		      .build();

	boolean isExist =  ldapAuthRepository.existsById(dn);
	if(isExist ==false) {
		ldapAuthRepository.save(ldapAuthUser);
	}else {
		logger.info("User with username "+ldapAuthUser.getUserName()+" is already exist ");
	}
}
 
Example #8
Source File: LdapIdentityLookup.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
    String searchFilter = environment.getProperty("lookup.user.filter");
    LOGGER.debug("Looking for a LDAP user's identifier using search filter [{}]", searchFilter);

    if (searchFilter != null) {
        identifierAttribute = LdapUtils.extractAttribute(searchFilter);

        LOGGER.info("User identifier is based on the [{}] attribute", identifierAttribute);

        userAttributes = new String [] {
                identifierAttribute, LDAP_ATTRIBUTE_GIVENNAME, LDAP_ATTRIBUTE_SURNAME,
                LDAP_ATTRIBUTE_MAIL, LDAP_ATTRIBUTE_DISPLAYNAME
        };
    } else {
        userAttributes = new String [] {
                LDAP_ATTRIBUTE_GIVENNAME, LDAP_ATTRIBUTE_SURNAME,
                LDAP_ATTRIBUTE_MAIL, LDAP_ATTRIBUTE_DISPLAYNAME
        };
    }

    // Base DN to search for users
    baseDn = LdapNameBuilder
            .newInstance(environment.getProperty("context.base"))
            .add(environment.getProperty("lookup.user.base", ""))
            .build();

    LOGGER.info("User search is based on DN [{}]", baseDn);
}
 
Example #9
Source File: LdapClient.java    From tutorials with MIT License 5 votes vote down vote up
public void create(final String username, final String password) {
    Name dn = LdapNameBuilder
      .newInstance()
      .add("ou", "users")
      .add("cn", username)
      .build();
    DirContextAdapter context = new DirContextAdapter(dn);

    context.setAttributeValues("objectclass", new String[]{"top", "person", "organizationalPerson", "inetOrgPerson"});
    context.setAttributeValue("cn", username);
    context.setAttributeValue("sn", username);
    context.setAttributeValue("userPassword", digestSHA(password));

    ldapTemplate.bind(context);
}
 
Example #10
Source File: LdapClient.java    From tutorials with MIT License 5 votes vote down vote up
public void modify(final String username, final String password) {
    Name dn = LdapNameBuilder
      .newInstance()
      .add("ou", "users")
      .add("cn", username)
      .build();
    DirContextOperations context = ldapTemplate.lookupContext(dn);

    context.setAttributeValues("objectclass", new String[]{"top", "person", "organizationalPerson", "inetOrgPerson"});
    context.setAttributeValue("cn", username);
    context.setAttributeValue("sn", username);
    context.setAttributeValue("userPassword", digestSHA(password));

    ldapTemplate.modifyAttributes(context);
}
 
Example #11
Source File: LdapClient.java    From tutorials with MIT License 5 votes vote down vote up
public void create(final String username, final String password) {
    Name dn = LdapNameBuilder
      .newInstance()
      .add("ou", "users")
      .add("cn", username)
      .build();
    DirContextAdapter context = new DirContextAdapter(dn);

    context.setAttributeValues("objectclass", new String[] { "top", "person", "organizationalPerson", "inetOrgPerson" });
    context.setAttributeValue("cn", username);
    context.setAttributeValue("sn", username);
    context.setAttributeValue("userPassword", digestSHA(password));

    ldapTemplate.bind(context);
}
 
Example #12
Source File: LdapClient.java    From tutorials with MIT License 5 votes vote down vote up
public void modify(final String username, final String password) {
    Name dn = LdapNameBuilder
      .newInstance()
      .add("ou", "users")
      .add("cn", username)
      .build();
    DirContextOperations context = ldapTemplate.lookupContext(dn);

    context.setAttributeValues("objectclass", new String[] { "top", "person", "organizationalPerson", "inetOrgPerson" });
    context.setAttributeValue("cn", username);
    context.setAttributeValue("sn", username);
    context.setAttributeValue("userPassword", digestSHA(password));

    ldapTemplate.modifyAttributes(context);
}
 
Example #13
Source File: OdmPersonDaoImpl.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
private LdapName buildDn(String country, String company, String fullname) {
       return LdapNameBuilder.newInstance()
               .add("c", country)
               .add("ou", company)
               .add("cn", fullname)
               .build();
}
 
Example #14
Source File: PersonDaoImpl.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
private LdapName buildDn(String country, String company, String fullname) {
       return LdapNameBuilder.newInstance()
               .add("c", country)
               .add("ou", company)
               .add("cn", fullname)
               .build();
}
 
Example #15
Source File: UserService.java    From spring-ldap with Apache License 2.0 4 votes vote down vote up
public LdapName toAbsoluteDn(Name relativeName) {
    return LdapNameBuilder.newInstance(baseLdapPath)
            .add(relativeName)
            .build();
}
 
Example #16
Source File: DepartmentRepoImpl.java    From spring-ldap with Apache License 2.0 4 votes vote down vote up
private List<String> getAllUnitsForDepartment(String department) {
    return ldapTemplate.list(LdapNameBuilder
            .newInstance(DEPARTMENTS_OU).add("ou", department).build(), new OuValueNameClassPairMapper());
}