use of javax.naming.NamingEnumeration in project karaf by apache.
the class LDAPCache method doGetUserRoles.
private String[] doGetUserRoles(String user, String userDn, String userDnNamespace) throws NamingException {
DirContext context = open();
SearchControls controls = new SearchControls();
if (options.getRoleSearchSubtree()) {
controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
} else {
controls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
}
String filter = options.getRoleFilter();
if (filter != null) {
filter = filter.replaceAll(Pattern.quote("%u"), Matcher.quoteReplacement(user));
filter = filter.replaceAll(Pattern.quote("%dn"), Matcher.quoteReplacement(userDn));
filter = filter.replaceAll(Pattern.quote("%fqdn"), Matcher.quoteReplacement(userDnNamespace));
filter = filter.replace("\\", "\\\\");
LOGGER.debug("Looking for the user roles in LDAP with ");
LOGGER.debug(" base DN: " + options.getRoleBaseDn());
LOGGER.debug(" filter: " + filter);
NamingEnumeration namingEnumeration = context.search(options.getRoleBaseDn(), filter, controls);
try {
List<String> rolesList = new ArrayList<>();
while (namingEnumeration.hasMore()) {
SearchResult result = (SearchResult) namingEnumeration.next();
Attributes attributes = result.getAttributes();
Attribute roles1 = attributes.get(options.getRoleNameAttribute());
if (roles1 != null) {
for (int i = 0; i < roles1.size(); i++) {
String role = (String) roles1.get(i);
if (role != null) {
LOGGER.debug("User {} is a member of role {}", user, role);
// handle role mapping
Set<String> roleMappings = tryMappingRole(role);
if (roleMappings.isEmpty()) {
rolesList.add(role);
} else {
for (String roleMapped : roleMappings) {
rolesList.add(roleMapped);
}
}
}
}
}
}
return rolesList.toArray(new String[rolesList.size()]);
} finally {
if (namingEnumeration != null) {
try {
namingEnumeration.close();
} catch (NamingException e) {
// Ignore
}
}
}
} else {
LOGGER.debug("The user role filter is null so no roles are retrieved");
return new String[] {};
}
}
use of javax.naming.NamingEnumeration in project wildfly by wildfly.
the class ServiceBasedNamingStoreTestCase method testStoredContext.
@Test
public void testStoredContext() throws Exception {
final ServiceName bindingName = ServiceName.JBOSS.append("foo-stored").append("again");
bindObject(bindingName, new Context() {
@Override
public Object lookup(Name name) throws NamingException {
if ("blah/blah2".equals(name.toString())) {
return new Integer(5);
}
return null;
}
@Override
public Object lookup(String name) throws NamingException {
return lookup(new CompositeName(name));
}
@Override
public void bind(Name name, Object obj) throws NamingException {
}
@Override
public void bind(String name, Object obj) throws NamingException {
}
@Override
public void rebind(Name name, Object obj) throws NamingException {
}
@Override
public void rebind(String name, Object obj) throws NamingException {
}
@Override
public void unbind(Name name) throws NamingException {
}
@Override
public void unbind(String name) throws NamingException {
}
@Override
public void rename(Name oldName, Name newName) throws NamingException {
}
@Override
public void rename(String oldName, String newName) throws NamingException {
}
@Override
public NamingEnumeration<NameClassPair> list(Name name) throws NamingException {
return null;
}
@Override
public NamingEnumeration<NameClassPair> list(String name) throws NamingException {
return null;
}
@Override
public NamingEnumeration<Binding> listBindings(Name name) throws NamingException {
if (!"hi/there".equals(name.toString()))
throw new IllegalArgumentException("Expected hi/there");
return null;
}
@Override
public NamingEnumeration<Binding> listBindings(String name) throws NamingException {
return null;
}
@Override
public void destroySubcontext(Name name) throws NamingException {
}
@Override
public void destroySubcontext(String name) throws NamingException {
}
@Override
public Context createSubcontext(Name name) throws NamingException {
return null;
}
@Override
public Context createSubcontext(String name) throws NamingException {
return null;
}
@Override
public Object lookupLink(Name name) throws NamingException {
return null;
}
@Override
public Object lookupLink(String name) throws NamingException {
return null;
}
@Override
public NameParser getNameParser(Name name) throws NamingException {
return null;
}
@Override
public NameParser getNameParser(String name) throws NamingException {
return null;
}
@Override
public Name composeName(Name name, Name prefix) throws NamingException {
return null;
}
@Override
public String composeName(String name, String prefix) throws NamingException {
return null;
}
@Override
public Object addToEnvironment(String propName, Object propVal) throws NamingException {
return null;
}
@Override
public Object removeFromEnvironment(String propName) throws NamingException {
return null;
}
@Override
public Hashtable<?, ?> getEnvironment() throws NamingException {
return null;
}
@Override
public void close() throws NamingException {
}
@Override
public String getNameInNamespace() throws NamingException {
return null;
}
});
final NamingContext ctx = new NamingContext(new CompositeName(), store, null);
final Object obj = ctx.lookup(new CompositeName("foo-stored/again/blah/blah2"));
ctx.listBindings("foo-stored/again/hi/there");
assertNotNull(obj);
assertEquals(new Integer(5), obj);
}
use of javax.naming.NamingEnumeration in project uPortal by Jasig.
the class SimpleLdapSecurityContext method authenticate.
/** Authenticates the user. */
public synchronized void authenticate() throws PortalSecurityException {
this.isauth = false;
ILdapServer ldapConn;
String propFile = ctxProperties.getProperty(LDAP_PROPERTIES_CONNECTION_NAME);
if (propFile != null && propFile.length() > 0)
ldapConn = LdapServices.getLdapServer(propFile);
else
ldapConn = LdapServices.getDefaultLdapServer();
String creds = new String(this.myOpaqueCredentials.credentialstring);
if (this.myPrincipal.UID != null && !this.myPrincipal.UID.trim().equals("") && this.myOpaqueCredentials.credentialstring != null && !creds.trim().equals("")) {
DirContext conn = null;
NamingEnumeration results = null;
StringBuffer user = new StringBuffer("(");
String first_name = null;
String last_name = null;
user.append(ldapConn.getUidAttribute()).append("=");
user.append(this.myPrincipal.UID).append(")");
log.debug("SimpleLdapSecurityContext: Looking for {}", user.toString());
try {
conn = ldapConn.getConnection();
// set up search controls
SearchControls searchCtls = new SearchControls();
searchCtls.setReturningAttributes(attributes);
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
// do lookup
if (conn != null) {
try {
results = conn.search(ldapConn.getBaseDN(), user.toString(), searchCtls);
if (results != null) {
if (!results.hasMore()) {
log.error("SimpleLdapSecurityContext: user not found: {}", this.myPrincipal.UID);
}
while (results != null && results.hasMore()) {
SearchResult entry = (SearchResult) results.next();
StringBuffer dnBuffer = new StringBuffer();
dnBuffer.append(entry.getName()).append(", ");
dnBuffer.append(ldapConn.getBaseDN());
Attributes attrs = entry.getAttributes();
first_name = getAttributeValue(attrs, ATTR_FIRSTNAME);
last_name = getAttributeValue(attrs, ATTR_LASTNAME);
// re-bind as user
conn.removeFromEnvironment(javax.naming.Context.SECURITY_PRINCIPAL);
conn.removeFromEnvironment(javax.naming.Context.SECURITY_CREDENTIALS);
conn.addToEnvironment(javax.naming.Context.SECURITY_PRINCIPAL, dnBuffer.toString());
conn.addToEnvironment(javax.naming.Context.SECURITY_CREDENTIALS, this.myOpaqueCredentials.credentialstring);
searchCtls = new SearchControls();
searchCtls.setReturningAttributes(new String[0]);
searchCtls.setSearchScope(SearchControls.OBJECT_SCOPE);
String attrSearch = "(" + ldapConn.getUidAttribute() + "=*)";
log.debug("SimpleLdapSecurityContext: Looking in {} for {}", dnBuffer.toString(), attrSearch);
conn.search(dnBuffer.toString(), attrSearch, searchCtls);
this.isauth = true;
this.myPrincipal.FullName = first_name + " " + last_name;
log.debug("SimpleLdapSecurityContext: User {} ({}) is authenticated", this.myPrincipal.UID, this.myPrincipal.FullName);
// Since LDAP is case-insensitive with respect to uid, force
// user name to lower case for use by the portal
this.myPrincipal.UID = this.myPrincipal.UID.toLowerCase();
}
// while (results != null && results.hasMore())
} else {
log.error("SimpleLdapSecurityContext: No such user: {}", this.myPrincipal.UID);
}
} catch (AuthenticationException ae) {
log.info("SimpleLdapSecurityContext: Password invalid for user: " + this.myPrincipal.UID);
} catch (Exception e) {
log.error("SimpleLdapSecurityContext: LDAP Error with user: " + this.myPrincipal.UID + "; ", e);
throw new PortalSecurityException("SimpleLdapSecurityContext: LDAP Error" + e + " with user: " + this.myPrincipal.UID);
} finally {
ldapConn.releaseConnection(conn);
}
} else {
log.error("LDAP Server Connection unavailable");
}
} catch (final NamingException ne) {
log.error("Error getting connection to LDAP server.", ne);
}
} else {
// If the principal and/or credential are missing, the context authentication
// simply fails. It should not be construed that this is an error. It happens for guest access.
log.info("Principal or OpaqueCredentials not initialized prior to authenticate");
}
// Ok...we are now ready to authenticate all of our subcontexts.
super.authenticate();
return;
}
use of javax.naming.NamingEnumeration in project simba-os by cegeka.
the class ActiveDirectoryLoginModule method addADGroupsToUser.
protected void addADGroupsToUser(LdapContext ldapContext, User user, String userCN) throws NamingException {
SearchControls searchControls = new SearchControls();
searchControls.setReturningAttributes(new String[] { "dn" });
searchControls.setSearchScope(searchScope);
GroupRepository groupRepository = GlobalContext.locate(GroupRepository.class);
String filterGroups = "(&(member=" + userCN + "," + searchBase + ")(objectcategory=group))";
NamingEnumeration results = ldapContext.search(searchBase, filterGroups, searchControls);
while (hasMoreResults(results)) {
String groupCN = ((SearchResult) results.next()).getName();
Group group = groupRepository.findByCN(groupCN);
if (group != null) {
user.addGroup(group);
}
}
}
use of javax.naming.NamingEnumeration in project zeppelin by apache.
the class ActiveDirectoryGroupRealm method getRoleNamesForUser.
private Set<String> getRoleNamesForUser(String username, LdapContext ldapContext) throws NamingException {
Set<String> roleNames = new LinkedHashSet<>();
SearchControls searchCtls = new SearchControls();
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
String userPrincipalName = username;
if (this.principalSuffix != null && userPrincipalName.indexOf('@') < 0) {
userPrincipalName += principalSuffix;
}
String searchFilter = "(&(objectClass=*)(userPrincipalName=" + userPrincipalName + "))";
Object[] searchArguments = new Object[] { userPrincipalName };
NamingEnumeration answer = ldapContext.search(searchBase, searchFilter, searchArguments, searchCtls);
while (answer.hasMoreElements()) {
SearchResult sr = (SearchResult) answer.next();
if (log.isDebugEnabled()) {
log.debug("Retrieving group names for user [" + sr.getName() + "]");
}
Attributes attrs = sr.getAttributes();
if (attrs != null) {
NamingEnumeration ae = attrs.getAll();
while (ae.hasMore()) {
Attribute attr = (Attribute) ae.next();
if (attr.getID().equals("memberOf")) {
Collection<String> groupNames = LdapUtils.getAllAttributeValues(attr);
if (log.isDebugEnabled()) {
log.debug("Groups found for user [" + username + "]: " + groupNames);
}
Collection<String> rolesForGroups = getRoleNamesForGroups(groupNames);
roleNames.addAll(rolesForGroups);
}
}
}
}
return roleNames;
}
Aggregations