Search in sources :

Example 66 with InitialDirContext

use of javax.naming.directory.InitialDirContext in project iaf by ibissource.

the class LdapFindMemberPipe method findMember.

private boolean findMember(String host, int port, String dnSearchIn, boolean useSsl, String dnFind, boolean recursiveSearch) throws NamingException {
    Hashtable<String, Object> env = new Hashtable<String, Object>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    String provUrl = retrieveUrl(host, port, dnSearchIn, useSsl);
    env.put(Context.PROVIDER_URL, provUrl);
    if (StringUtils.isNotEmpty(cf.getUsername())) {
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, cf.getUsername());
        env.put(Context.SECURITY_CREDENTIALS, cf.getPassword());
    } else {
        env.put(Context.SECURITY_AUTHENTICATION, "none");
    }
    DirContext ctx = null;
    try {
        try {
            ctx = new InitialDirContext(env);
        } catch (CommunicationException e) {
            log.info("Cannot create constructor for DirContext [" + e.getMessage() + "], will try again with dummy SocketFactory", e);
            env.put("java.naming.ldap.factory.socket", DummySSLSocketFactory.class.getName());
            ctx = new InitialLdapContext(env, null);
        }
        Attribute attrs = ctx.getAttributes("").get("member");
        if (attrs != null) {
            boolean found = false;
            for (int i = 0; i < attrs.size() && !found; i++) {
                String dnFound = (String) attrs.get(i);
                if (dnFound.equalsIgnoreCase(dnFind)) {
                    found = true;
                } else {
                    if (recursiveSearch) {
                        found = findMember(host, port, dnFound, useSsl, dnFind, recursiveSearch);
                    }
                }
            }
            return found;
        }
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException e) {
                log.warn("Exception closing DirContext", e);
            }
        }
    }
    return false;
}
Also used : CommunicationException(javax.naming.CommunicationException) Attribute(javax.naming.directory.Attribute) Hashtable(java.util.Hashtable) InitialLdapContext(javax.naming.ldap.InitialLdapContext) NamingException(javax.naming.NamingException) DirContext(javax.naming.directory.DirContext) InitialDirContext(javax.naming.directory.InitialDirContext) InitialDirContext(javax.naming.directory.InitialDirContext)

Example 67 with InitialDirContext

use of javax.naming.directory.InitialDirContext in project jetty.project by eclipse.

the class LdapLoginModule method bindingLogin.

/**
     * binding authentication check
     * This method of authentication works only if the user branch of the DIT (ldap tree)
     * has an ACI (access control instruction) that allow the access to any user or at least
     * for the user that logs in.
     *
     * @param username the user name
     * @param password the password
     * @return true always
     * @throws LoginException if unable to bind the login
     * @throws NamingException if failure to bind login
     */
public boolean bindingLogin(String username, Object password) throws LoginException, NamingException {
    SearchResult searchResult = findUser(username);
    String userDn = searchResult.getNameInNamespace();
    LOG.info("Attempting authentication: " + userDn);
    Hashtable<Object, Object> environment = getEnvironment();
    if (userDn == null || "".equals(userDn)) {
        throw new NamingException("username may not be empty");
    }
    environment.put(Context.SECURITY_PRINCIPAL, userDn);
    // RFC 4513 section 6.3.1, protect against ldap server implementations that allow successful binding on empty passwords
    if (password == null || "".equals(password)) {
        throw new NamingException("password may not be empty");
    }
    environment.put(Context.SECURITY_CREDENTIALS, password);
    DirContext dirContext = new InitialDirContext(environment);
    List<String> roles = getUserRolesByDn(dirContext, userDn);
    UserInfo userInfo = new UserInfo(username, null, roles);
    setCurrentUser(new JAASUserInfo(userInfo));
    setAuthenticated(true);
    return true;
}
Also used : SearchResult(javax.naming.directory.SearchResult) NamingException(javax.naming.NamingException) InitialDirContext(javax.naming.directory.InitialDirContext) DirContext(javax.naming.directory.DirContext) InitialDirContext(javax.naming.directory.InitialDirContext)

Example 68 with InitialDirContext

use of javax.naming.directory.InitialDirContext in project presto by prestodb.

the class LdapFilter method authenticate.

private Principal authenticate(String user, String password) throws AuthenticationException {
    Map<String, String> environment = createEnvironment(user, password);
    InitialDirContext context = null;
    try {
        context = createDirContext(environment);
        checkForGroupMembership(user, context);
        log.debug("Authentication successful for user %s", user);
        return new LdapPrincipal(user);
    } catch (javax.naming.AuthenticationException e) {
        String formattedAsciiMessage = format("Invalid credentials: %s", JAVA_ISO_CONTROL.removeFrom(e.getMessage()));
        log.debug("Authentication failed for user [%s]. %s", user, e.getMessage());
        throw new AuthenticationException(UNAUTHORIZED, formattedAsciiMessage, e);
    } catch (NamingException e) {
        log.debug("Authentication failed", e.getMessage());
        throw new AuthenticationException(INTERNAL_SERVER_ERROR, "Authentication failed", e);
    } finally {
        closeContext(context);
    }
}
Also used : NamingException(javax.naming.NamingException) JndiUtils.getInitialDirContext(com.facebook.presto.server.security.util.jndi.JndiUtils.getInitialDirContext) InitialDirContext(javax.naming.directory.InitialDirContext)

Example 69 with InitialDirContext

use of javax.naming.directory.InitialDirContext in project OpenAM by OpenRock.

the class Step4 method getLdapHostAndPort.

// Method to get hostname and port number with the
// provided Domain Name for Active Directory user data store.
private String[] getLdapHostAndPort(String domainName) throws NamingException, IOException {
    if (!domainName.endsWith(".")) {
        domainName += '.';
    }
    DirContext ictx = null;
    // The resource record type A is defined in RFC 1035. 
    try {
        Hashtable env = new Hashtable();
        env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
        ictx = new InitialDirContext(env);
        Attributes attributes = ictx.getAttributes(domainName, new String[] { "A" });
        Attribute attrib = attributes.get("A");
        if (attrib == null) {
            throw new NamingException();
        }
    } catch (NamingException e) {
        // throw exception.
        throw e;
    }
    // then look for the LDAP server
    String serverHostName = null;
    String serverPortStr = null;
    final String ldapServer = "_ldap._tcp." + domainName;
    try {
        // Attempting to resolve ldapServer to SRV record.
        // This is a mechanism defined in MSDN, querying 
        // SRV records for _ldap._tcp.DOMAINNAME.
        // and get host and port from domain.
        Attributes attributes = ictx.getAttributes(ldapServer, new String[] { "SRV" });
        Attribute attr = attributes.get("SRV");
        if (attr == null) {
            throw new NamingException();
        }
        String[] srv = attr.get().toString().split(" ");
        String hostNam = srv[3];
        serverHostName = hostNam.substring(0, hostNam.length() - 1);
        if ((serverHostName != null) && serverHostName.length() > 0) {
            getContext().setSessionAttribute(SessionAttributeNames.USER_STORE_HOST, serverHostName);
        }
        serverPortStr = srv[2];
    } catch (NamingException e) {
        // throw exception.
        throw e;
    }
    // try to connect to LDAP port to make sure this machine 
    // has LDAP service
    int serverPort = Integer.parseInt(serverPortStr);
    if ((serverPort > 0) && (serverPort < 65535)) {
        getContext().setSessionAttribute(SessionAttributeNames.USER_STORE_PORT, serverPortStr);
    }
    try {
        new Socket(serverHostName, serverPort).close();
    } catch (IOException e) {
        throw e;
    }
    String[] hostAndPort = new String[2];
    hostAndPort[0] = serverHostName;
    hostAndPort[1] = serverPortStr;
    return hostAndPort;
}
Also used : Attribute(javax.naming.directory.Attribute) Hashtable(java.util.Hashtable) Attributes(javax.naming.directory.Attributes) NamingException(javax.naming.NamingException) DirContext(javax.naming.directory.DirContext) InitialDirContext(javax.naming.directory.InitialDirContext) InitialDirContext(javax.naming.directory.InitialDirContext) IOException(java.io.IOException) Socket(java.net.Socket)

Example 70 with InitialDirContext

use of javax.naming.directory.InitialDirContext in project Activiti by Activiti.

the class LDAPConnectionUtil method createDirectoryContext.

public static InitialDirContext createDirectoryContext(LDAPConfigurator ldapConfigurator, String principal, String credentials) {
    Properties properties = new Properties();
    properties.put(Context.INITIAL_CONTEXT_FACTORY, ldapConfigurator.getInitialContextFactory());
    properties.put(Context.PROVIDER_URL, ldapConfigurator.getServer() + ":" + ldapConfigurator.getPort());
    properties.put(Context.SECURITY_AUTHENTICATION, ldapConfigurator.getSecurityAuthentication());
    properties.put(Context.SECURITY_PRINCIPAL, principal);
    properties.put(Context.SECURITY_CREDENTIALS, credentials);
    if (ldapConfigurator.getCustomConnectionParameters() != null) {
        for (String customParameter : ldapConfigurator.getCustomConnectionParameters().keySet()) {
            properties.put(customParameter, ldapConfigurator.getCustomConnectionParameters().get(customParameter));
        }
    }
    InitialDirContext context;
    try {
        context = new InitialDirContext(properties);
    } catch (NamingException e) {
        LOGGER.warn("Could not create InitialDirContext for LDAP connection : " + e.getMessage());
        throw new ActivitiException("Could not create InitialDirContext for LDAP connection : " + e.getMessage(), e);
    }
    return context;
}
Also used : ActivitiException(org.activiti.engine.ActivitiException) NamingException(javax.naming.NamingException) InitialDirContext(javax.naming.directory.InitialDirContext) Properties(java.util.Properties)

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