use of org.springframework.ldap.core.DirContextOperations in project opennms by OpenNMS.
the class KerberosLdapAuthenticationProvider method authenticate.
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) authentication;
/*
* The incoming username will be in the form of a Kerberos user principal name,
* e.g. user@EXAMPLE.ORG. We typically need to strip off the realm name before
* doing any LDAP operations with the username.
*/
String validatedUsername = trimRealmFromUsername(m_kerberosClient.login(auth.getName(), auth.getCredentials().toString()));
DirContextOperations ldapUserEntry = m_ldapUserSearch.searchForUser(validatedUsername);
Collection<? extends GrantedAuthority> grantedAuthorities = m_ldapAuthoritiesPopulator.getGrantedAuthorities(ldapUserEntry, validatedUsername);
UserDetails userDetails = new User(validatedUsername, "notUsed", true, true, true, true, grantedAuthorities);
UsernamePasswordAuthenticationToken output = new UsernamePasswordAuthenticationToken(userDetails, auth.getCredentials(), grantedAuthorities);
return output;
}
use of org.springframework.ldap.core.DirContextOperations in project nifi by apache.
the class LdapUserGroupProvider method load.
/**
* Reloads the tenants.
*/
private void load(final ContextSource contextSource) {
// create the ldapTemplate based on the context source. use a single source context to use the same connection
// to support paging when configured
final SingleContextSource singleContextSource = new SingleContextSource(contextSource.getReadOnlyContext());
final LdapTemplate ldapTemplate = new LdapTemplate(singleContextSource);
try {
final List<User> userList = new ArrayList<>();
final List<Group> groupList = new ArrayList<>();
// group dn -> user identifiers lookup
final Map<String, Set<String>> groupToUserIdentifierMappings = new HashMap<>();
// user dn -> user lookup
final Map<String, User> userLookup = new HashMap<>();
if (performUserSearch) {
// search controls
final SearchControls userControls = new SearchControls();
userControls.setSearchScope(userSearchScope.ordinal());
// consider paging support for users
final DirContextProcessor userProcessor;
if (pageSize == null) {
userProcessor = new NullDirContextProcessor();
} else {
userProcessor = new PagedResultsDirContextProcessor(pageSize);
}
// looking for objects matching the user object class
final AndFilter userFilter = new AndFilter();
userFilter.and(new EqualsFilter("objectClass", userObjectClass));
// if a filter has been provided by the user, we add it to the filter
if (StringUtils.isNotBlank(userSearchFilter)) {
userFilter.and(new HardcodedFilter(userSearchFilter));
}
do {
userList.addAll(ldapTemplate.search(userSearchBase, userFilter.encode(), userControls, new AbstractContextMapper<User>() {
@Override
protected User doMapFromContext(DirContextOperations ctx) {
// get the user identity
final String identity = getUserIdentity(ctx);
// build the user
final User user = new User.Builder().identifierGenerateFromSeed(identity).identity(identity).build();
// store the user for group member later
userLookup.put(getReferencedUserValue(ctx), user);
if (StringUtils.isNotBlank(userGroupNameAttribute)) {
final Attribute attributeGroups = ctx.getAttributes().get(userGroupNameAttribute);
if (attributeGroups == null) {
logger.warn("User group name attribute [" + userGroupNameAttribute + "] does not exist. Ignoring group membership.");
} else {
try {
final NamingEnumeration<String> groupValues = (NamingEnumeration<String>) attributeGroups.getAll();
while (groupValues.hasMoreElements()) {
// store the group -> user identifier mapping
groupToUserIdentifierMappings.computeIfAbsent(groupValues.next(), g -> new HashSet<>()).add(user.getIdentifier());
}
} catch (NamingException e) {
throw new AuthorizationAccessException("Error while retrieving user group name attribute [" + userIdentityAttribute + "].");
}
}
}
return user;
}
}, userProcessor));
} while (hasMorePages(userProcessor));
}
if (performGroupSearch) {
final SearchControls groupControls = new SearchControls();
groupControls.setSearchScope(groupSearchScope.ordinal());
// consider paging support for groups
final DirContextProcessor groupProcessor;
if (pageSize == null) {
groupProcessor = new NullDirContextProcessor();
} else {
groupProcessor = new PagedResultsDirContextProcessor(pageSize);
}
// looking for objects matching the group object class
AndFilter groupFilter = new AndFilter();
groupFilter.and(new EqualsFilter("objectClass", groupObjectClass));
// if a filter has been provided by the user, we add it to the filter
if (StringUtils.isNotBlank(groupSearchFilter)) {
groupFilter.and(new HardcodedFilter(groupSearchFilter));
}
do {
groupList.addAll(ldapTemplate.search(groupSearchBase, groupFilter.encode(), groupControls, new AbstractContextMapper<Group>() {
@Override
protected Group doMapFromContext(DirContextOperations ctx) {
final String dn = ctx.getDn().toString();
// get the group identity
final String name = getGroupName(ctx);
// get the value of this group that may associate it to users
final String referencedGroupValue = getReferencedGroupValue(ctx);
if (!StringUtils.isBlank(groupMemberAttribute)) {
Attribute attributeUsers = ctx.getAttributes().get(groupMemberAttribute);
if (attributeUsers == null) {
logger.warn("Group member attribute [" + groupMemberAttribute + "] does not exist. Ignoring group membership.");
} else {
try {
final NamingEnumeration<String> userValues = (NamingEnumeration<String>) attributeUsers.getAll();
while (userValues.hasMoreElements()) {
final String userValue = userValues.next();
if (performUserSearch) {
// find the user by it's referenced attribute and add the identifier to this group
final User user = userLookup.get(userValue);
// ensure the user is known
if (user != null) {
groupToUserIdentifierMappings.computeIfAbsent(referencedGroupValue, g -> new HashSet<>()).add(user.getIdentifier());
} else {
logger.warn(String.format("%s contains member %s but that user was not found while searching users. Ignoring group membership.", name, userValue));
}
} else {
// since performUserSearch is false, then the referenced group attribute must be blank... the user value must be the dn
final String userDn = userValue;
final String userIdentity;
if (useDnForUserIdentity) {
// use the user value to avoid the unnecessary look up
userIdentity = userDn;
} else {
// lookup the user to extract the user identity
userIdentity = getUserIdentity((DirContextAdapter) ldapTemplate.lookup(userDn));
}
// build the user
final User user = new User.Builder().identifierGenerateFromSeed(userIdentity).identity(userIdentity).build();
// add this user
userList.add(user);
groupToUserIdentifierMappings.computeIfAbsent(referencedGroupValue, g -> new HashSet<>()).add(user.getIdentifier());
}
}
} catch (NamingException e) {
throw new AuthorizationAccessException("Error while retrieving group name attribute [" + groupNameAttribute + "].");
}
}
}
// build this group
final Group.Builder groupBuilder = new Group.Builder().identifierGenerateFromSeed(name).name(name);
// add all users that were associated with this referenced group attribute
if (groupToUserIdentifierMappings.containsKey(referencedGroupValue)) {
groupToUserIdentifierMappings.remove(referencedGroupValue).forEach(userIdentifier -> groupBuilder.addUser(userIdentifier));
}
return groupBuilder.build();
}
}, groupProcessor));
} while (hasMorePages(groupProcessor));
// any remaining groupDn's were referenced by a user but not found while searching groups
groupToUserIdentifierMappings.forEach((referencedGroupValue, userIdentifiers) -> {
logger.warn(String.format("[%s] are members of %s but that group was not found while searching users. Ignoring group membership.", StringUtils.join(userIdentifiers, ", "), referencedGroupValue));
});
} else {
// since performGroupSearch is false, then the referenced user attribute must be blank... the group value must be the dn
// groups are not being searched so lookup any groups identified while searching users
groupToUserIdentifierMappings.forEach((groupDn, userIdentifiers) -> {
final String groupName;
if (useDnForGroupName) {
// use the dn to avoid the unnecessary look up
groupName = groupDn;
} else {
groupName = getGroupName((DirContextAdapter) ldapTemplate.lookup(groupDn));
}
// define the group
final Group.Builder groupBuilder = new Group.Builder().identifierGenerateFromSeed(groupName).name(groupName);
// add each user
userIdentifiers.forEach(userIdentifier -> groupBuilder.addUser(userIdentifier));
// build the group
groupList.add(groupBuilder.build());
});
}
// record the updated tenants
tenants.set(new TenantHolder(new HashSet<>(userList), new HashSet<>(groupList)));
} finally {
singleContextSource.destroy();
}
}
use of org.springframework.ldap.core.DirContextOperations in project apollo by ctripcorp.
the class ApolloLdapAuthenticationProvider method authenticate.
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication, this.messages.getMessage("LdapAuthenticationProvider.onlySupports", "Only UsernamePasswordAuthenticationToken is supported"));
UsernamePasswordAuthenticationToken userToken = (UsernamePasswordAuthenticationToken) authentication;
String username = userToken.getName();
String password = (String) authentication.getCredentials();
if (this.logger.isDebugEnabled()) {
this.logger.debug("Processing authentication request for user: " + username);
}
if (!StringUtils.hasLength(username)) {
throw new BadCredentialsException(this.messages.getMessage("LdapAuthenticationProvider.emptyUsername", "Empty Username"));
}
if (!StringUtils.hasLength(password)) {
throw new BadCredentialsException(this.messages.getMessage("AbstractLdapAuthenticationProvider.emptyPassword", "Empty Password"));
}
Assert.notNull(password, "Null password was supplied in authentication token");
DirContextOperations userData = this.doAuthentication(userToken);
String loginId = userData.getStringAttribute(properties.getMapping().getLoginId());
UserDetails user = this.userDetailsContextMapper.mapUserFromContext(userData, loginId, this.loadUserAuthorities(userData, loginId, (String) authentication.getCredentials()));
return this.createSuccessfulAuthentication(userToken, user);
}
use of org.springframework.ldap.core.DirContextOperations in project kylo by Teradata.
the class LdapLoginModule method doLogin.
/* (non-Javadoc)
* @see com.thinkbiganalytics.auth.jaas.AbstractLoginModule#doLogin()
*/
@Override
protected boolean doLogin() throws Exception {
final NameCallback nameCallback = new NameCallback("Username: ");
final PasswordCallback passwordCallback = new PasswordCallback("Password: ", false);
handle(nameCallback, passwordCallback);
if (nameCallback.getName() == null) {
throw new AccountException("No username provided for authentication");
}
Principal userPrincipal = new UsernamePrincipal(nameCallback.getName());
String password = new String(passwordCallback.getPassword());
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userPrincipal, password);
try {
log.debug("Authenticating: {}", userPrincipal);
DirContextOperations dirContext = this.authenticator.authenticate(authentication);
log.debug("Successfully Authenticated: {}", userPrincipal);
setUserPrincipal(userPrincipal);
for (GrantedAuthority grant : this.authoritiesPopulator.getGrantedAuthorities(dirContext, nameCallback.getName())) {
String groupName = grant.getAuthority();
log.debug("Found group for {}: {}", userPrincipal, groupName);
if (groupName != null) {
addNewGroupPrincipal(groupName);
}
}
return true;
} catch (BadCredentialsException e) {
throw new CredentialException(e.getMessage());
}
}
use of org.springframework.ldap.core.DirContextOperations in project spring-security by spring-projects.
the class BindAuthenticatorTests method testAuthenticationWithUserSearch.
@Test
public void testAuthenticationWithUserSearch() throws Exception {
// DirContextAdapter ctx = new DirContextAdapter(new
// DistinguishedName("uid=bob,ou=people"));
this.authenticator.setUserSearch(new FilterBasedLdapUserSearch("ou=people", "(uid={0})", this.contextSource));
this.authenticator.afterPropertiesSet();
DirContextOperations result = this.authenticator.authenticate(this.bob);
// ensure we are getting the same attributes back
assertThat(result.getStringAttribute("cn")).isEqualTo("Bob Hamilton");
// SEC-1444
this.authenticator.setUserSearch(new FilterBasedLdapUserSearch("ou=people", "(cn={0})", this.contextSource));
this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("mouse, jerry", "jerryspassword"));
this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("slash/guy", "slashguyspassword"));
// SEC-1661
this.authenticator.setUserSearch(new FilterBasedLdapUserSearch("ou=\\\"quoted people\\\"", "(cn={0})", this.contextSource));
this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("quote\"guy", "quoteguyspassword"));
this.authenticator.setUserSearch(new FilterBasedLdapUserSearch("", "(cn={0})", this.contextSource));
this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("quote\"guy", "quoteguyspassword"));
}
Aggregations