use of javax.naming.directory.DirContext in project Openfire by igniterealtime.
the class LdapUserProvider method loadUser.
@Override
public User loadUser(String username) throws UserNotFoundException {
if (username.contains("@")) {
if (!XMPPServer.getInstance().isLocal(new JID(username))) {
throw new UserNotFoundException("Cannot load user of remote server: " + username);
}
username = username.substring(0, username.lastIndexOf("@"));
}
// Un-escape username.
username = JID.unescapeNode(username);
DirContext ctx = null;
try {
String userDN = manager.findUserDN(username);
// Load record.
String[] attributes = new String[] { manager.getUsernameField(), manager.getNameField(), manager.getEmailField(), "createTimestamp", "modifyTimestamp" };
ctx = manager.getContext(manager.getUsersBaseDN(username));
Attributes attrs = ctx.getAttributes(userDN, attributes);
String name = null;
Attribute nameField = attrs.get(manager.getNameField());
if (nameField != null) {
name = (String) nameField.get();
}
String email = null;
Attribute emailField = attrs.get(manager.getEmailField());
if (emailField != null) {
email = (String) emailField.get();
}
Date creationDate = new Date();
Attribute creationDateField = attrs.get("createTimestamp");
if (creationDateField != null && "".equals(((String) creationDateField.get()).trim())) {
creationDate = parseLDAPDate((String) creationDateField.get());
}
Date modificationDate = new Date();
Attribute modificationDateField = attrs.get("modifyTimestamp");
if (modificationDateField != null && "".equals(((String) modificationDateField.get()).trim())) {
modificationDate = parseLDAPDate((String) modificationDateField.get());
}
// Escape the username so that it can be used as a JID.
username = JID.escapeNode(username);
// As defined by RFC5803.
Attribute authPassword = attrs.get("authPassword");
User user = new User(username, name, email, creationDate, modificationDate);
if (authPassword != null) {
// The authPassword attribute can be multivalued.
// Not sure if this is the right API to loop through them.
NamingEnumeration values = authPassword.getAll();
while (values.hasMore()) {
Attribute authPasswordValue = (Attribute) values.next();
String[] parts = ((String) authPasswordValue.get()).split("$");
String[] authInfo = parts[1].split(":");
String[] authValue = parts[2].split(":");
String scheme = parts[0].trim();
// We only support SCRAM-SHA-1 at the moment.
if ("SCRAM-SHA-1".equals(scheme)) {
int iterations = Integer.valueOf(authInfo[0].trim());
String salt = authInfo[1].trim();
String storedKey = authValue[0].trim();
String serverKey = authValue[1].trim();
user.setSalt(salt);
user.setStoredKey(storedKey);
user.setServerKey(serverKey);
user.setIterations(iterations);
break;
}
}
}
return user;
} catch (Exception e) {
throw new UserNotFoundException(e);
} finally {
try {
if (ctx != null) {
ctx.close();
}
} catch (Exception ignored) {
// Ignore.
}
}
}
use of javax.naming.directory.DirContext in project hudson-2.x by hudson.
the class LDAPSecurityRealm method inferRootDN.
/**
* Infer the root DN.
*
* @return null if not found.
*/
private String inferRootDN(String server) {
try {
Hashtable<String, String> props = new Hashtable<String, String>();
if (managerDN != null) {
props.put(Context.SECURITY_PRINCIPAL, managerDN);
props.put(Context.SECURITY_CREDENTIALS, getManagerPassword());
}
props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
props.put(Context.PROVIDER_URL, getServerUrl() + '/');
DirContext ctx = new InitialDirContext(props);
Attributes atts = ctx.getAttributes("");
Attribute a = atts.get("defaultNamingContext");
if (// this entry is available on Active Directory. See http://msdn2.microsoft.com/en-us/library/ms684291(VS.85).aspx
a != null)
return a.toString();
a = atts.get("namingcontexts");
if (a == null) {
LOGGER.warning("namingcontexts attribute not found in root DSE of " + server);
return null;
}
return a.get().toString();
} catch (NamingException e) {
LOGGER.log(Level.WARNING, "Failed to connect to LDAP to infer Root DN for " + server, e);
return null;
}
}
use of javax.naming.directory.DirContext in project platformlayer by platformlayer.
the class ITOpenLdapService method testLdap.
private void testLdap(String ldapUrl, Secret adminPassword) throws NamingException {
Hashtable<String, String> env = new Hashtable<String, String>();
String sp = "com.sun.jndi.ldap.LdapCtxFactory";
env.put(Context.INITIAL_CONTEXT_FACTORY, sp);
env.put(Context.PROVIDER_URL, ldapUrl);
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "cn=Manager,dc=test,dc=platformlayer,dc=org");
env.put(Context.SECURITY_CREDENTIALS, adminPassword.plaintext());
DirContext ctx = new InitialDirContext(env);
NamingEnumeration results = ctx.list("dc=test,dc=platformlayer,dc=org");
while (results.hasMore()) {
NameClassPair sr = (NameClassPair) results.next();
System.out.println(sr.getNameInNamespace());
}
ctx.close();
}
use of javax.naming.directory.DirContext in project jforum2 by rafaelsteil.
the class LDAPAuthenticator method validateLogin.
/**
* @see net.jforum.sso.LoginAuthenticator#validateLogin(java.lang.String, java.lang.String, java.util.Map)
*/
public User validateLogin(String username, String password, Map extraParams) {
Hashtable environment = this.prepareEnvironment();
StringBuffer principal = new StringBuffer(256).append(SystemGlobals.getValue(ConfigKeys.LDAP_LOGIN_PREFIX)).append(username).append(',').append(SystemGlobals.getValue(ConfigKeys.LDAP_LOGIN_SUFFIX));
environment.put(Context.SECURITY_PRINCIPAL, principal.toString());
environment.put(Context.SECURITY_CREDENTIALS, password);
DirContext dir = null;
try {
dir = new InitialDirContext(environment);
String lookupPrefix = SystemGlobals.getValue(ConfigKeys.LDAP_LOOKUP_PREFIX);
String lookupSuffix = SystemGlobals.getValue(ConfigKeys.LDAP_LOOKUP_SUFFIX);
if (lookupPrefix == null || lookupPrefix.length() == 0) {
lookupPrefix = SystemGlobals.getValue(ConfigKeys.LDAP_LOGIN_PREFIX);
}
if (lookupSuffix == null || lookupSuffix.length() == 0) {
lookupSuffix = SystemGlobals.getValue(ConfigKeys.LDAP_LOGIN_SUFFIX);
}
String lookupPrincipal = lookupPrefix + username + "," + lookupSuffix;
Attribute att = dir.getAttributes(lookupPrincipal).get(SystemGlobals.getValue(ConfigKeys.LDAP_FIELD_EMAIL));
SSOUtils utils = new SSOUtils();
if (!utils.userExists(username)) {
String email = att != null ? (String) att.get() : "noemail";
utils.register("ldap", email);
}
return utils.getUser();
} catch (AuthenticationException e) {
return null;
} catch (NamingException e) {
return null;
} finally {
if (dir != null) {
try {
dir.close();
} catch (NamingException e) {
//close jndi context
}
}
}
}
use of javax.naming.directory.DirContext in project spring-security by spring-projects.
the class PasswordComparisonAuthenticatorMockTests method ldapCompareOperationIsUsedWhenPasswordIsNotRetrieved.
// ~ Methods
// ========================================================================================================
@Test
public void ldapCompareOperationIsUsedWhenPasswordIsNotRetrieved() throws Exception {
final DirContext dirCtx = mock(DirContext.class);
final BaseLdapPathContextSource source = mock(BaseLdapPathContextSource.class);
final BasicAttributes attrs = new BasicAttributes();
attrs.put(new BasicAttribute("uid", "bob"));
PasswordComparisonAuthenticator authenticator = new PasswordComparisonAuthenticator(source);
authenticator.setUserDnPatterns(new String[] { "cn={0},ou=people" });
// Get the mock to return an empty attribute set
when(source.getReadOnlyContext()).thenReturn(dirCtx);
when(dirCtx.getAttributes(eq("cn=Bob,ou=people"), any(String[].class))).thenReturn(attrs);
when(dirCtx.getNameInNamespace()).thenReturn("dc=springframework,dc=org");
// Setup a single return value (i.e. success)
final NamingEnumeration searchResults = new BasicAttributes("", null).getAll();
when(dirCtx.search(eq("cn=Bob,ou=people"), eq("(userPassword={0})"), any(Object[].class), any(SearchControls.class))).thenReturn(searchResults);
authenticator.authenticate(new UsernamePasswordAuthenticationToken("Bob", "bobspassword"));
}
Aggregations