use of javax.naming.directory.InitialDirContext in project opentheso by miledrousset.
the class LDAPAuthenticator method dnFromUser.
private String dnFromUser(String username) throws NamingException {
Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
props.put(Context.PROVIDER_URL, "ldap://ldap.mondomaine.fr");
props.put(Context.REFERRAL, "ignore");
InitialDirContext context = new InitialDirContext(props);
SearchControls ctrls = new SearchControls();
ctrls.setReturningAttributes(new String[] { authBean.getFirstnameLdap(), authBean.getNameLdap() });
ctrls.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration<SearchResult> answers = context.search(authBean.getScope(), "(" + authBean.getUidLdap() + "=" + username + ")", ctrls);
if (answers != null) {
SearchResult result = answers.next();
return result.getNameInNamespace();
}
return null;
}
use of javax.naming.directory.InitialDirContext in project opentheso by miledrousset.
the class LDAPAuthenticator method login.
/* (non-Javadoc)
* @see fr.persee.aldo.auth.Authenticator#login(java.lang.String, java.lang.String)
*/
public Account login(String login, String password) {
Account acc = null;
try {
String dn = dnFromUser(login);
if (dn == null) {
// TODO gerer exception
return null;
}
env.put(Context.SECURITY_PRINCIPAL, dn);
env.put(Context.SECURITY_CREDENTIALS, password);
InitialDirContext context = new InitialDirContext(env);
SearchControls ctrls = new SearchControls();
ctrls.setReturningAttributes(new String[] { authBean.getFirstnameLdap(), authBean.getNameLdap(), authBean.getMailLdap() });
ctrls.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration<SearchResult> answers;
answers = context.search(authBean.getScope(), "(" + authBean.getUidLdap() + "=" + login + ")", ctrls);
SearchResult result;
result = answers.next();
// System.out.println();
String firstname = result.getAttributes().get(authBean.getFirstnameLdap()).get().toString();
String name = result.getAttributes().get(authBean.getNameLdap()).get().toString();
String mail = result.getAttributes().get(authBean.getMailLdap()).get().toString();
// User
User user = new User();
user.setUser(login);
user.setFirstname(firstname);
user.setLastname(name);
user.setMail(mail);
user.setUid(login);
// Account
acc = new Account();
acc.setBaseId(authBean.getBaseId());
acc.setUser(user);
} catch (NamingException e) {
}
return acc;
}
use of javax.naming.directory.InitialDirContext in project pentaho-kettle by pentaho.
the class MailValidation method getMX.
private static ArrayList<String> getMX(String hostName) throws NamingException {
// Perform a DNS lookup for MX records in the domain
Hashtable<String, String> env = new Hashtable<String, String>();
env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
DirContext ictx = new InitialDirContext(env);
Attributes attrs = ictx.getAttributes(hostName, new String[] { "MX" });
Attribute attr = attrs.get("MX");
// if we don't have an MX record, try the machine itself
if ((attr == null) || (attr.size() == 0)) {
attrs = ictx.getAttributes(hostName, new String[] { "A" });
attr = attrs.get("A");
if (attr == null) {
throw new NamingException(BaseMessages.getString(PKG, "MailValidator.NoMatchName", hostName));
}
}
// Huzzah! we have machines to try. Return them as an array list
// NOTE: We SHOULD take the preference into account to be absolutely
// correct. This is left as an exercise for anyone who cares.
ArrayList<String> res = new ArrayList<String>();
NamingEnumeration<?> en = attr.getAll();
while (en.hasMore()) {
String x = (String) en.next();
String[] f = x.split(" ");
if (f[1].endsWith(".")) {
f[1] = f[1].substring(0, (f[1].length() - 1));
}
res.add(f[1]);
}
return res;
}
use of javax.naming.directory.InitialDirContext in project alfresco-repository by Alfresco.
the class LDAPAuthenticationComponentImpl method authenticateImpl.
/**
* Implement the authentication method
*/
protected void authenticateImpl(String userName, char[] password) throws AuthenticationException {
if (logger.isTraceEnabled()) {
logger.trace("Authentication for user: " + AuthenticationUtil.maskUsername(userName));
}
// Distinguished name of user.
String userDN;
AuthenticationDiagnostic diagnostic = new AuthenticationDiagnostic();
if (userNameFormat == null) {
// If we aren't using a fixed name format, do a search to resolve the user DN
userDN = ldapNameResolver.resolveDistinguishedName(userName, diagnostic);
Object[] params = { userName, userDN };
diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_LOOKEDUP_USER, true, params);
} else // Otherwise, use the format, but disallow leading or trailing whitespace in the user ID as this can result in
// ghost users (MNT-2597)
{
if (!userName.equals(userName.trim())) {
throw new AuthenticationException("Invalid user ID with leading or trailing whitespace");
}
// we are using a fixed name format,
userDN = String.format(userNameFormat, new Object[] { escapeUserName(userName, escapeCommasInBind) });
Object[] params = { userName, userDN, userNameFormat };
diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_FORMAT_USER, true, params);
}
InitialDirContext ctx = null;
try {
ctx = ldapInitialContextFactory.getInitialDirContext(userDN, new String(password), diagnostic);
// Authentication has been successful.
// Set the current user, they are now authenticated.
setCurrentUser(escapeUserName(userName, escapeCommasInUid));
} finally {
if (ctx != null) {
try {
ctx.close();
} catch (NamingException e) {
clearCurrentSecurityContext();
throw new AuthenticationException("Failed to close connection", e);
}
}
}
}
use of javax.naming.directory.InitialDirContext in project alfresco-repository by Alfresco.
the class LDAPInitialDirContextFactoryImpl method buildInitialDirContext.
private InitialDirContext buildInitialDirContext(Hashtable<String, String> env, int pageSize, AuthenticationDiagnostic diagnostic) throws AuthenticationException {
String securityPrincipal = env.get(Context.SECURITY_PRINCIPAL);
String providerURL = env.get(Context.PROVIDER_URL);
if (isSSLSocketFactoryRequired()) {
KeyStore trustStore = initTrustStore();
AlfrescoSSLSocketFactory.initTrustedSSLSocketFactory(trustStore);
env.put("java.naming.ldap.factory.socket", AlfrescoSSLSocketFactory.class.getName());
}
if (diagnostic == null) {
diagnostic = new AuthenticationDiagnostic();
}
try {
// If a page size has been requested, use LDAP v3 paging
if (pageSize > 0) {
InitialLdapContext ctx = new InitialLdapContext(env, null);
ctx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.CRITICAL) });
return ctx;
} else {
InitialDirContext ret = new InitialDirContext(env);
Object[] args = { providerURL, securityPrincipal };
diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTED, true, args);
return ret;
}
} catch (javax.naming.AuthenticationException ax) {
Object[] args1 = { securityPrincipal };
Object[] args = { providerURL, securityPrincipal };
diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTED, true, args);
diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_AUTHENTICATION, false, args1);
// wrong user/password - if we get this far the connection is O.K
Object[] args2 = { securityPrincipal, ax.getLocalizedMessage() };
throw new AuthenticationException("authentication.err.authentication", diagnostic, args2, ax);
} catch (CommunicationException ce) {
Object[] args1 = { providerURL };
diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTING, false, args1);
StringBuffer message = new StringBuffer();
message.append(ce.getClass().getName() + ", " + ce.getMessage());
Throwable cause = ce.getCause();
while (cause != null) {
message.append(", ");
message.append(cause.getClass().getName() + ", " + cause.getMessage());
cause = cause.getCause();
}
// failed to connect
Object[] args = { providerURL, message.toString() };
throw new AuthenticationException("authentication.err.communication", diagnostic, args, cause);
} catch (NamingException nx) {
Object[] args = { providerURL };
diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTING, false, args);
StringBuffer message = new StringBuffer();
message.append(nx.getClass().getName() + ", " + nx.getMessage());
Throwable cause = nx.getCause();
while (cause != null) {
message.append(", ");
message.append(cause.getClass().getName() + ", " + cause.getMessage());
cause = cause.getCause();
}
// failed to connect
Object[] args1 = { providerURL, message.toString() };
throw new AuthenticationException("authentication.err.connection", diagnostic, args1, nx);
} catch (IOException e) {
Object[] args = { providerURL, securityPrincipal };
diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTED, true, args);
throw new AuthenticationException("Unable to encode LDAP v3 request controls", e);
}
}
Aggregations