use of org.springframework.ldap.filter.EqualsFilter 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.filter.EqualsFilter in project trainning by fernandotomasio.
the class LDAPNetworkUserDAO method authenticate.
@Override
public NetworkUserDTO authenticate(String uid, String password) throws DAOException {
boolean result = false;
try {
AndFilter filter = new AndFilter();
filter.and(new EqualsFilter("objectclass", "inetOrgPerson")).and(new EqualsFilter("uid", uid));
result = ldapTemplate.authenticate(DistinguishedName.EMPTY_PATH, filter.toString(), password);
} catch (AuthenticationException e) {
Logger.getLogger(LDAPNetworkUserDAO.class.getName()).log(Level.INFO, null, e);
throw new DAOException(MessageHelper.getMessage("systemUsers.authenticate.error"));
}
if (result == true) {
return find(uid);
} else {
return null;
}
}
use of org.springframework.ldap.filter.EqualsFilter in project cxf by apache.
the class LdapUtils method getAttributeOfEntries.
public static List<String> getAttributeOfEntries(LdapTemplate ldapTemplate, String baseDN, String objectClass, List<Filter> filters, String searchAttribute) {
List<String> ldapAttributes = null;
AttributesMapper<Object> mapper = new AttributesMapper<Object>() {
public Object mapFromAttributes(Attributes attrs) throws NamingException {
NamingEnumeration<? extends Attribute> attrEnum = attrs.getAll();
while (attrEnum.hasMore()) {
return attrEnum.next().get();
}
return null;
}
};
String[] searchAttributes = new String[] { searchAttribute };
AndFilter filter = new AndFilter();
filter.and(new EqualsFilter("objectclass", objectClass));
if (filters != null) {
for (Filter f : filters) {
filter.and(f);
}
}
List<?> result = ldapTemplate.search((baseDN == null) ? "" : baseDN, filter.toString(), SearchControls.SUBTREE_SCOPE, searchAttributes, mapper);
if (result != null && !result.isEmpty()) {
ldapAttributes = CastUtils.cast((List<?>) result);
}
return ldapAttributes;
}
use of org.springframework.ldap.filter.EqualsFilter in project cxf by apache.
the class LdapUtils method getAttributesOfEntry.
public static Map<String, Attribute> getAttributesOfEntry(LdapTemplate ldapTemplate, String baseDN, String objectClass, String filterAttributeName, String filterAttributeValue, String[] searchAttributes) {
Map<String, Attribute> ldapAttributes = null;
AttributesMapper<Map<String, Attribute>> mapper = new AttributesMapper<Map<String, Attribute>>() {
public Map<String, Attribute> mapFromAttributes(Attributes attrs) throws NamingException {
Map<String, Attribute> map = new HashMap<>();
NamingEnumeration<? extends Attribute> attrEnum = attrs.getAll();
while (attrEnum.hasMore()) {
Attribute att = attrEnum.next();
map.put(att.getID(), att);
}
return map;
}
};
AndFilter filter = new AndFilter();
filter.and(new EqualsFilter("objectclass", objectClass)).and(new EqualsFilter(filterAttributeName, filterAttributeValue));
List<Map<String, Attribute>> result = ldapTemplate.search((baseDN == null) ? "" : baseDN, filter.toString(), SearchControls.SUBTREE_SCOPE, searchAttributes, mapper);
if (result != null && !result.isEmpty()) {
ldapAttributes = result.get(0);
}
return ldapAttributes;
}
use of org.springframework.ldap.filter.EqualsFilter in project cxf by apache.
the class LdapGroupClaimsHandler method retrieveClaimValues.
public ProcessedClaimCollection retrieveClaimValues(ClaimCollection claims, ClaimsParameters parameters) {
boolean found = false;
for (Claim claim : claims) {
if (claim.getClaimType().toString().equals(this.groupURI)) {
found = true;
break;
}
}
if (!found) {
return new ProcessedClaimCollection();
}
String user = null;
Principal principal = parameters.getPrincipal();
if (principal instanceof KerberosPrincipal) {
KerberosPrincipal kp = (KerberosPrincipal) principal;
StringTokenizer st = new StringTokenizer(kp.getName(), "@");
user = st.nextToken();
} else if (principal instanceof X500Principal) {
X500Principal x500p = (X500Principal) principal;
LOG.warning("Unsupported principal type X500: " + x500p.getName());
} else if (principal != null) {
user = principal.getName();
if (user == null) {
LOG.warning("Principal name must not be null");
}
} else {
LOG.warning("Principal is null");
}
if (user == null) {
return new ProcessedClaimCollection();
}
if (!LdapUtils.isDN(user)) {
Name dn = LdapUtils.getDnOfEntry(ldap, this.userBaseDn, this.getUserObjectClass(), this.getUserNameAttribute(), user);
if (dn != null) {
user = dn.toString();
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("DN for (" + this.getUserNameAttribute() + "=" + user + ") found: " + user);
}
} else {
LOG.warning("DN not found for user '" + user + "'");
return new ProcessedClaimCollection();
}
}
if (LOG.isLoggable(Level.FINER)) {
LOG.finer("Retrieve groups for user " + user);
}
List<Filter> filters = new ArrayList<>();
filters.add(new EqualsFilter(this.groupMemberAttribute, user));
if (customFilters != null && !customFilters.isEmpty()) {
filters.addAll(customFilters);
}
List<String> groups = LdapUtils.getAttributeOfEntries(ldap, this.groupBaseDn, this.getGroupObjectClass(), filters, "cn");
if (groups == null || groups.isEmpty()) {
if (LOG.isLoggable(Level.INFO)) {
LOG.info("No groups found for user '" + user + "'");
}
return new ProcessedClaimCollection();
}
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("Groups for user '" + parameters.getPrincipal().getName() + "': " + groups);
}
String scope = null;
if (getAppliesToScopeMapping() != null && !getAppliesToScopeMapping().isEmpty() && parameters.getAppliesToAddress() != null) {
scope = getAppliesToScopeMapping().get(parameters.getAppliesToAddress());
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("AppliesTo matches with scope: " + scope);
}
}
String regex = this.groupNameGlobalFilter;
regex = regex.replaceAll(ROLE, ".*");
Pattern globalPattern = Pattern.compile(regex);
// If AppliesTo value can be mapped to a Scope Name
// ex. https://localhost/doubleit/services/doubleittransport -> Demo
Pattern scopePattern = null;
if (scope != null) {
regex = this.groupNameScopedFilter;
regex = regex.replaceAll(SCOPE, scope).replaceAll(ROLE, ".*");
scopePattern = Pattern.compile(regex);
}
List<String> filteredGroups = new ArrayList<>();
for (String group : groups) {
if (scopePattern != null && scopePattern.matcher(group).matches()) {
// Group matches the scoped filter
// ex. (default groupNameScopeFilter)
// Demo_User -> Role=User
// Demo_Admin -> Role=Admin
String filter = this.groupNameScopedFilter;
final String role;
if (isUseFullGroupNameAsValue()) {
role = group;
} else {
role = parseRole(group, filter.replaceAll(SCOPE, scope));
}
filteredGroups.add(role);
} else {
if (globalPattern.matcher(group).matches()) {
// Group matches the global filter
// ex. (default groupNameGlobalFilter)
// User -> Role=User
// Admin -> Role=Admin
final String role;
if (isUseFullGroupNameAsValue()) {
role = group;
} else {
role = parseRole(group, this.groupNameGlobalFilter);
}
filteredGroups.add(role);
} else if (LOG.isLoggable(Level.FINER)) {
LOG.finer("Group '" + group + "' doesn't match scoped and global group filter");
}
}
}
LOG.info("Filtered groups: " + filteredGroups);
if (filteredGroups.isEmpty()) {
LOG.info("No matching groups found for user '" + principal + "'");
return new ProcessedClaimCollection();
}
ProcessedClaimCollection claimsColl = new ProcessedClaimCollection();
ProcessedClaim c = new ProcessedClaim();
c.setClaimType(URI.create(this.groupURI));
c.setPrincipal(principal);
c.setValues(new ArrayList<>(filteredGroups));
// c.setIssuer(issuer);
// c.setOriginalIssuer(originalIssuer);
// c.setNamespace(namespace);
claimsColl.add(c);
return claimsColl;
}
Aggregations