Search in sources :

Example 56 with InitialDirContext

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;
}
Also used : SearchControls(javax.naming.directory.SearchControls) SearchResult(javax.naming.directory.SearchResult) InitialDirContext(javax.naming.directory.InitialDirContext) Properties(java.util.Properties)

Example 57 with InitialDirContext

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;
}
Also used : Account(mom.trd.opentheso.bdd.account.Account) User(mom.trd.opentheso.bdd.account.User) SearchControls(javax.naming.directory.SearchControls) SearchResult(javax.naming.directory.SearchResult) NamingException(javax.naming.NamingException) InitialDirContext(javax.naming.directory.InitialDirContext)

Example 58 with InitialDirContext

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;
}
Also used : Attribute(javax.naming.directory.Attribute) Hashtable(java.util.Hashtable) Attributes(javax.naming.directory.Attributes) ArrayList(java.util.ArrayList) NamingException(javax.naming.NamingException) DirContext(javax.naming.directory.DirContext) InitialDirContext(javax.naming.directory.InitialDirContext) InitialDirContext(javax.naming.directory.InitialDirContext)

Example 59 with InitialDirContext

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);
            }
        }
    }
}
Also used : AuthenticationException(org.alfresco.repo.security.authentication.AuthenticationException) AuthenticationDiagnostic(org.alfresco.repo.security.authentication.AuthenticationDiagnostic) NamingException(javax.naming.NamingException) InitialDirContext(javax.naming.directory.InitialDirContext)

Example 60 with InitialDirContext

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);
    }
}
Also used : CommunicationException(javax.naming.CommunicationException) AuthenticationException(org.alfresco.repo.security.authentication.AuthenticationException) InitialDirContext(javax.naming.directory.InitialDirContext) IOException(java.io.IOException) KeyStore(java.security.KeyStore) AlfrescoSSLSocketFactory(org.alfresco.repo.security.authentication.AlfrescoSSLSocketFactory) InitialLdapContext(javax.naming.ldap.InitialLdapContext) AuthenticationDiagnostic(org.alfresco.repo.security.authentication.AuthenticationDiagnostic) NamingException(javax.naming.NamingException) PagedResultsControl(javax.naming.ldap.PagedResultsControl)

Aggregations

InitialDirContext (javax.naming.directory.InitialDirContext)131 DirContext (javax.naming.directory.DirContext)71 NamingException (javax.naming.NamingException)67 Hashtable (java.util.Hashtable)51 Attributes (javax.naming.directory.Attributes)34 Attribute (javax.naming.directory.Attribute)24 SearchResult (javax.naming.directory.SearchResult)22 SearchControls (javax.naming.directory.SearchControls)19 IOException (java.io.IOException)11 CommunicationException (javax.naming.CommunicationException)11 Test (org.junit.Test)11 Properties (java.util.Properties)10 BasicAttributes (javax.naming.directory.BasicAttributes)9 ArrayList (java.util.ArrayList)8 LoginException (javax.security.auth.login.LoginException)8 NameClassPair (javax.naming.NameClassPair)7 HashSet (java.util.HashSet)6 NamingEnumeration (javax.naming.NamingEnumeration)6 BasicAttribute (javax.naming.directory.BasicAttribute)6 ResultCodeException (eu.bcvsolutions.idm.core.api.exception.ResultCodeException)5