org.springframework.security.ldap.SpringSecurityLdapTemplate Java Examples

The following examples show how to use org.springframework.security.ldap.SpringSecurityLdapTemplate. 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: SpringLdapExternalUidTranslation.java    From unitime with Apache License 2.0 6 votes vote down vote up
public String uid2ext(String uid) {
 	String externalIdAttribute = ApplicationProperty.AuthenticationLdapIdAttribute.value();
 	if ("uid".equals(externalIdAttribute)) return uid; // Nothing to translate
     try {
     	
ContextSource source = (ContextSource)SpringApplicationContextHolder.getBean("unitimeLdapContextSource");

String query = ApplicationProperty.AuthenticationLdapLogin2UserId.value();

SpringSecurityLdapTemplate template = new SpringSecurityLdapTemplate(source);
DirContextOperations user = template.retrieveEntry(query.replaceAll("\\{0\\}", uid), new String[] {externalIdAttribute});

return user == null ? null : user.getStringAttribute(externalIdAttribute);

     } catch (Exception e) {
     	sLog.warn("Unable to translate uid to " + externalIdAttribute + ": " + e.getMessage());
     }
     
     return null;
 }
 
Example #2
Source File: SpringLdapExternalUidTranslation.java    From unitime with Apache License 2.0 6 votes vote down vote up
public String ext2uid(String externalUserId) {
 	String externalIdAttribute = ApplicationProperty.AuthenticationLdapIdAttribute.value();
 	if ("uid".equals(externalIdAttribute)) return externalUserId; // Nothing to translate
     try {
     	
     	ContextSource source = (ContextSource)SpringApplicationContextHolder.getBean("unitimeLdapContextSource");

String query = ApplicationProperty.AuthenticationLdapUserId2Login.value().replace("%", externalIdAttribute);

SpringSecurityLdapTemplate template = new SpringSecurityLdapTemplate(source);
DirContextOperations user = template.retrieveEntry(query.replaceAll("\\{0\\}", externalIdAttribute), new String[] {"uid"});

return user == null ? null : user.getStringAttribute("uid");

     } catch (Exception e) {
     	sLog.warn("Unable to translate " + externalIdAttribute + " to uid: " + e.getMessage());
     }
     return null;
 }
 
Example #3
Source File: FilterLdapByGroupUserSearch.java    From apollo with Apache License 2.0 5 votes vote down vote up
@Override
public DirContextOperations searchForUser(String username) {
  if (logger.isDebugEnabled()) {
    logger.debug("Searching for user '" + username + "', with user search " + this);
  }
  SpringSecurityLdapTemplate template = new SpringSecurityLdapTemplate(this.contextSource);
  template.setSearchControls(searchControls);
  return template
      .searchForObject(groupBase, groupSearch, ctx -> {
        if (!MEMBER_UID_ATTR_NAME.equals(groupMembershipAttrName)) {
          String[] members = ((DirContextAdapter) ctx)
              .getStringAttributes(groupMembershipAttrName);
          for (String item : members) {
            LdapName memberDn = LdapUtils.newLdapName(item);
            LdapName memberRdn = LdapUtils
                .removeFirst(memberDn, LdapUtils.newLdapName(searchBase));
            String rdnValue = LdapUtils.getValue(memberRdn, rdnKey).toString();
            if (rdnValue.equalsIgnoreCase(username)) {
              return new DirContextAdapter(memberRdn.toString());
            }
          }
          throw new UsernameNotFoundException("User " + username + " not found in directory.");
        }
        String[] memberUids = ((DirContextAdapter) ctx)
            .getStringAttributes(groupMembershipAttrName);
        for (String memberUid : memberUids) {
          if (memberUid.equalsIgnoreCase(username)) {
            Name name = searchUserById(memberUid);
            LdapName ldapName = LdapUtils.newLdapName(name);
            LdapName ldapRdn = LdapUtils
                .removeFirst(ldapName, LdapUtils.newLdapName(searchBase));
            return new DirContextAdapter(ldapRdn);
          }
        }
        throw new UsernameNotFoundException("User " + username + " not found in directory.");
      });
}
 
Example #4
Source File: LdapConfig.java    From fiat with Apache License 2.0 5 votes vote down vote up
@Bean
SpringSecurityLdapTemplate springSecurityLdapTemplate() throws Exception {
  DefaultSpringSecurityContextSource contextSource =
      new DefaultSpringSecurityContextSource(configProps.url);
  contextSource.setUserDn(configProps.managerDn);
  contextSource.setPassword(configProps.managerPassword);
  contextSource.afterPropertiesSet();

  return new SpringSecurityLdapTemplate(contextSource);
}
 
Example #5
Source File: LdapSearchContext.java    From hesperides with GNU General Public License v3.0 5 votes vote down vote up
private static DirContextOperations searchCN(DirContext dirContext, String cn, String base, String searchFilter) {
    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    try {
        // Durant cet appel, SpringSecurityLdapTemplate logue parfois des "Ignoring PartialResultException"
        return SpringSecurityLdapTemplate.searchForSingleEntryInternal(dirContext, searchControls, base, searchFilter, new Object[]{cn});
    } catch (NamingException exception) {
        throw LdapUtils.convertLdapException(exception);
    }
}
 
Example #6
Source File: SpringLdapExternalUidLookup.java    From unitime with Apache License 2.0 5 votes vote down vote up
@Override
public UserInfo doLookup(String uid) throws Exception {
	try {
		ContextSource source = (ContextSource)SpringApplicationContextHolder.getBean("unitimeLdapContextSource");
		
		String query = ApplicationProperty.AuthenticationLdapIdentify.value(); 
		String idAttributeName = ApplicationProperty.AuthenticationLdapIdAttribute.value();

		SpringSecurityLdapTemplate template = new SpringSecurityLdapTemplate(source);
		DirContextOperations user = template.retrieveEntry(query.replaceAll("\\{0\\}", uid), new String[] {"uid", idAttributeName, "cn", "givenName", "sn", "mail"});

		if (user == null || user.getStringAttribute(idAttributeName) == null)
			return null;
           
       	UserInfo info = new UserInfo();
       	info.setExternalId(user.getStringAttribute(idAttributeName));
       	
       	info.setUserName(user.getStringAttribute("uid"));
       	if (info.getUserName() == null) info.setUserName(uid);
       	info.setName(user.getStringAttribute("cn"));
       	info.setFirstName(user.getStringAttribute("givenName"));
       	info.setLastName(user.getStringAttribute("sn"));
       	info.setEmail(user.getStringAttribute("mail"));

       	if (info.getEmail() == null) {
           	String email = info.getUserName() + "@";
       		for (String x: user.getNameInNamespace().split(","))
       			if (x.startsWith("dc=")) email += (email.endsWith("@") ? "" : ".") + x.substring(3);
           	if (!email.endsWith("@")) info.setEmail(email);
       	}
       	
       	return info;
	} catch (Exception e) {
		sLog.warn("Lookup for " + uid + " failed: " + e.getMessage());
	}

	return null;
}
 
Example #7
Source File: FilterLdapByGroupUserSearch.java    From apollo with Apache License 2.0 4 votes vote down vote up
private Name searchUserById(String userId) {
  SpringSecurityLdapTemplate template = new SpringSecurityLdapTemplate(this.contextSource);
  template.setSearchControls(searchControls);
  return template.searchForObject(query().where(this.loginIdAttrName).is(userId),
      ctx -> ((DirContextAdapter) ctx).getDn());
}
 
Example #8
Source File: PasswordComparisonAuthenticator.java    From ranger with Apache License 2.0 4 votes vote down vote up
public DirContextOperations authenticate(final Authentication authentication) {
	Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class,
			authentication,
			"Can only process UsernamePasswordAuthenticationToken objects");
	// locate the user and check the password

	DirContextOperations user = null;
	String username = authentication.getName();
	String password = (String) authentication.getCredentials();

	Iterator dns = getUserDns(username).iterator();

	SpringSecurityLdapTemplate ldapTemplate = new SpringSecurityLdapTemplate(
			getContextSource());

	while (dns.hasNext() && user == null) {
		final String userDn = (String) dns.next();

		try {
			user = ldapTemplate.retrieveEntry(userDn, getUserAttributes());
		} catch (NameNotFoundException ignore) {
		}
	}

	if (user == null && getUserSearch() != null) {
		user = getUserSearch().searchForUser(username);
	}

	if (user == null) {
		throw new UsernameNotFoundException("User not found: " + username);
	}

	if (logger.isDebugEnabled()) {
		logger.debug("Performing LDAP compare of password attribute '"
				+ passwordAttributeName + "' for user '" + user.getDn()
				+ "'");
	}

	String encodedPassword = passwordEncoder.encodePassword(password, null);
	byte[] passwordBytes = encodedPassword.getBytes();

	if (!ldapTemplate.compare(user.getDn().toString(),
			passwordAttributeName, passwordBytes)) {
		throw new BadCredentialsException(messages.getMessage(
				"PasswordComparisonAuthenticator.badCredentials",
				"Bad credentials"));
	}

	return user;
}