use of javax.naming.directory.DirContext in project Openfire by igniterealtime.
the class LdapVCardProvider method getLdapAttributes.
/**
* Creates a mapping of requested LDAP attributes to their values for the given user.
*
* @param username User we are looking up in LDAP.
* @return Map of LDAP attribute to setting.
*/
private Map<String, String> getLdapAttributes(String username) {
// Un-escape username
username = JID.unescapeNode(username);
Map<String, String> map = new HashMap<>();
DirContext ctx = null;
try {
String userDN = manager.findUserDN(username);
ctx = manager.getContext(manager.getUsersBaseDN(username));
Attributes attrs = ctx.getAttributes(userDN, template.getAttributes());
for (String attribute : template.getAttributes()) {
javax.naming.directory.Attribute attr = attrs.get(attribute);
String value;
if (attr == null) {
Log.debug("LdapVCardProvider: No ldap value found for attribute '" + attribute + "'");
value = "";
} else {
Object ob = attrs.get(attribute).get();
Log.debug("LdapVCardProvider: Found attribute " + attribute + " of type: " + ob.getClass());
if (ob instanceof String) {
value = (String) ob;
} else {
value = Base64.encodeBytes((byte[]) ob);
}
}
Log.debug("LdapVCardProvider: Ldap attribute '" + attribute + "'=>'" + value + "'");
map.put(attribute, value);
}
return map;
} catch (Exception e) {
Log.error(e.getMessage(), e);
return Collections.emptyMap();
} finally {
try {
if (ctx != null) {
ctx.close();
}
} catch (Exception e) {
// Ignore.
}
}
}
use of javax.naming.directory.DirContext in project orientdb by orientechnologies.
the class OStorageRemote method parseServerURLs.
/**
* Parse the URLs. Multiple URLs must be separated by semicolon (;)
*/
protected void parseServerURLs() {
String lastHost = null;
int dbPos = url.indexOf('/');
if (dbPos == -1) {
// SHORT FORM
addHost(url);
lastHost = url;
name = url;
} else {
name = url.substring(url.lastIndexOf("/") + 1);
for (String host : url.substring(0, dbPos).split(ADDRESS_SEPARATOR)) {
lastHost = host;
addHost(host);
}
}
synchronized (serverURLs) {
if (serverURLs.size() == 1 && OGlobalConfiguration.NETWORK_BINARY_DNS_LOADBALANCING_ENABLED.getValueAsBoolean()) {
// LOOK FOR LOAD BALANCING DNS TXT RECORD
final String primaryServer = lastHost;
OLogManager.instance().debug(this, "Retrieving URLs from DNS '%s' (timeout=%d)...", primaryServer, OGlobalConfiguration.NETWORK_BINARY_DNS_LOADBALANCING_TIMEOUT.getValueAsInteger());
try {
final Hashtable<String, String> env = new Hashtable<String, String>();
env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
env.put("com.sun.jndi.ldap.connect.timeout", OGlobalConfiguration.NETWORK_BINARY_DNS_LOADBALANCING_TIMEOUT.getValueAsString());
final DirContext ictx = new InitialDirContext(env);
final String hostName = !primaryServer.contains(":") ? primaryServer : primaryServer.substring(0, primaryServer.indexOf(":"));
final Attributes attrs = ictx.getAttributes(hostName, new String[] { "TXT" });
final Attribute attr = attrs.get("TXT");
if (attr != null) {
for (int i = 0; i < attr.size(); ++i) {
String configuration = (String) attr.get(i);
if (configuration.startsWith("\""))
configuration = configuration.substring(1, configuration.length() - 1);
if (configuration != null) {
serverURLs.clear();
final String[] parts = configuration.split(" ");
for (String part : parts) {
if (part.startsWith("s=")) {
addHost(part.substring("s=".length()));
}
}
}
}
}
} catch (NamingException ignore) {
}
}
}
}
use of javax.naming.directory.DirContext in project spring-security by spring-projects.
the class ActiveDirectoryLdapAuthenticationProvider method doAuthentication.
@Override
protected DirContextOperations doAuthentication(UsernamePasswordAuthenticationToken auth) {
String username = auth.getName();
String password = (String) auth.getCredentials();
DirContext ctx = bindAsUser(username, password);
try {
return searchForUser(ctx, username);
} catch (NamingException e) {
logger.error("Failed to locate directory entry for authenticated user: " + username, e);
throw badCredentials(e);
} finally {
LdapUtils.closeContext(ctx);
}
}
use of javax.naming.directory.DirContext in project spring-security by spring-projects.
the class SpringSecurityLdapTemplateITests method namingExceptionIsTranslatedCorrectly.
// @Test
// public void testNameExistsForInValidNameFails() {
// assertThat(template.nameExists("ou=doesntexist,dc=springframework,dc=org")).isFalse();
// }
//
// @Test
// public void testNameExistsForValidNameSucceeds() {
// assertThat(template.nameExists("ou=groups,dc=springframework,dc=org")).isTrue();
// }
@Test
public void namingExceptionIsTranslatedCorrectly() {
try {
template.executeReadOnly(new ContextExecutor() {
public Object executeWithContext(DirContext dirContext) throws NamingException {
throw new NamingException();
}
});
fail("Expected UncategorizedLdapException on NamingException");
} catch (UncategorizedLdapException expected) {
}
}
use of javax.naming.directory.DirContext in project spring-security by spring-projects.
the class LdapUserDetailsManager method getUserAuthorities.
/**
*
* @param dn the distinguished name of the entry - may be either relative to the base
* context or a complete DN including the name of the context (either is supported).
* @param username the user whose roles are required.
* @return the granted authorities returned by the group search
*/
@SuppressWarnings("unchecked")
List<GrantedAuthority> getUserAuthorities(final DistinguishedName dn, final String username) {
SearchExecutor se = new SearchExecutor() {
public NamingEnumeration<SearchResult> executeSearch(DirContext ctx) throws NamingException {
DistinguishedName fullDn = LdapUtils.getFullDn(dn, ctx);
SearchControls ctrls = new SearchControls();
ctrls.setReturningAttributes(new String[] { groupRoleAttributeName });
return ctx.search(groupSearchBase, groupSearchFilter, new String[] { fullDn.toUrl(), username }, ctrls);
}
};
AttributesMapperCallbackHandler roleCollector = new AttributesMapperCallbackHandler(roleMapper);
template.search(se, roleCollector);
return roleCollector.getList();
}
Aggregations