Login with Network User (LDAP)

3

I have an LDAP server in my company, and a network user is required to log on to the machine. We would like that after the user is already logged in the machine, when using the network or some application in the intranet it is not necessary to inform again user and password. That through LDAP it was possible to issue some authentication in which the login was passed automatically.

Do you have such a possibility? If so, does anyone know a way for me to base myself?

    
asked by anonymous 16.09.2014 / 19:40

2 answers

0

I have part of the solution, I hope it helps. With the class below you can connect to the active directory via java.

There is a method in this class, authentication, which expects two parameters, the LDAP username and password.

You can use it in two ways:

  • Validate user and password (for this, enter the LDAP user and password, ex: authentication("filipe","senhateste"));

  • Validate if the user exists in LDAP (for this enter the username and password), however the password must be blank eg: authentication("filipe","")

  • There is an example in the last class of this answer.

    With this class you would be able to allow an LDAP user to authenticate to your system with the same network login and password.

    You would not find a method to find out, perhaps in the windows directories, if there is the LDAP user.

    import java.util.Hashtable;
    
    import javax.naming.AuthenticationException;
    import javax.naming.Context;
    import javax.naming.NamingEnumeration;
    import javax.naming.NamingException;
    import javax.naming.directory.Attributes;
    import javax.naming.directory.DirContext;
    import javax.naming.directory.InitialDirContext;
    import javax.naming.directory.SearchControls;
    import javax.naming.directory.SearchResult;
    
    @SuppressWarnings("rawtypes")
    public class LdapAuthentication {  
    
    
        /** 
         * Classe que realiza a conexão e autenticação ao LDAP 
         *  
         * @author Adriano Anderson 
         */  
    
        /* 
         * Singleton 
         */  
        protected static LdapAuthentication instanceLdap;  
    
        /* 
         * Implementação do Initial context para LDAP 
         */  
        public static String INITIAL_CTX = "com.sun.jndi.ldap.LdapCtxFactory";  
    
        /* 
         * Servidor LDAP 
         */  
        public static String SERVIDOR = "ldap://10.92.10.24:389"; //Defina aqui o ip onde está o ldap. o que vem após os ":" é a porta do ldap 
    
        /* 
         * Tipo de conexão realizada 
         */  
        public static String CONNECTION_TYPE = "simple";  
    
        /* 
         * Nome distinto do admin 
         */  
        public static String ADMIN_DN = "proxy_user";  
    
        /* 
         * Senha 
         */  
        public static String ADMIN_PW = "123456";  
    
        /* 
         * Diretório Base 
         */  
        public static String BASE_DN = "dc=cpbad,dc=cpb,dc=com,dc=br";  
    
        /* 
         * Mensagem de Erro de Conexão ao Ldap 
         */  
        public static String MSG_ERROR_LDAP_CONNECTION = "Não foi possível obter um contexto LDAP";  
    
        /* 
         * Mensagem de Erro sobre Validação do Login e Password 
         */  
        public static String MSG_ERROR_LDAP_VALIDATION_USER = "Username ou Password Inválida";  
    
        private LdapAuthentication() {  
            super();  
        }  
    
        /** 
         * Obtém a mesma instância de LdapAuthentication para todas as chamadas 
         *  
         * @author Adriano Anderson 
         * @return um objeto LdapAuthentication 
         */  
        public static LdapAuthentication getInstance() {  
    
            if (instanceLdap == null) {  
                instanceLdap = new LdapAuthentication();  
            }  
    
            return instanceLdap;  
        }  
    
        /** 
         * Método responsável por realizar a chamada para autenticação via ldap do 
         * login e password passados como parâmetros. 
         *  
         * @author Adriano Anderson 
         */  
        public boolean authentication(String login, String password) {  
    
            DirContext ctx = null;  
            SearchControls sc = null;  
            String filtro = null;  
            NamingEnumeration cursor = null;  
            boolean bResult = false;  
    
            /* 
             * Cria conexão padrão com LDAP 
             */  
            ctx = createLdapConnection();  
    
            if (ctx != null) {  
    
                sc = new SearchControls();  
                sc.setSearchScope(SearchControls.SUBTREE_SCOPE);  
                /* 
                 * Define atributos de retorno da consulta 
                 */  
                String[] atributosParaRetornar = { "distinguishedName","sAMAccountType" };  
                sc.setReturningAttributes(atributosParaRetornar);  
                /* 
                 * Especifica login para consulta 
                 */  
                filtro = "(&(sAMAccountName=" + login + "))";  
    
                try {  
                    cursor = ctx.search(BASE_DN, filtro, sc);  
    
                    if (cursor.hasMoreElements()) {  
    
                        SearchResult result = (SearchResult) cursor.nextElement();  
                        Attributes att = result.getAttributes();  
                        String dn = (String) att.get("distinguishedName").get();  
                        //String st = (String) att.get("sAMAccountType").get();
    
                        /* 
                         * Se o login existe, tenta autenticar no LDAP com a senha 
                         * fornecida pelo usuário 
                         */  
                        bResult = validateUser(dn, password);  
                    }  
    
                } catch (NamingException e) {  
                    System.out.println(MSG_ERROR_LDAP_CONNECTION);  
                    e.printStackTrace();  
                }  
            }  
            return bResult;  
        }  
    
        /** 
         * Método responsável por realizar a conexão padrão com o Ldap. 
         *  
         * @author Adriano Anderson 
         */ 
    
        @SuppressWarnings("unchecked")
        private DirContext createLdapConnection() {  
    
            DirContext ctx = null;  
            Hashtable env = new Hashtable();  
    
            // Especifica INITIAL CONTEXT  
            env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CTX);  
    
            // Especifica o IP/Nome e a porta do servidor LDAP  
            env.put(Context.PROVIDER_URL, SERVIDOR);  
    
            // Usuário ADMIN  
            env.put(Context.SECURITY_PRINCIPAL, ADMIN_DN);  
    
            // Senha ADMIN  
            env.put(Context.SECURITY_CREDENTIALS, ADMIN_PW);  
    
            // Tipo de Conexão  
            env.put(Context.SECURITY_AUTHENTICATION, CONNECTION_TYPE);  
    
            try {  
                // Cria um Initial Context  
                ctx = new InitialDirContext(env);  
    
            } catch (NamingException e) {  
                System.out.println(MSG_ERROR_LDAP_CONNECTION);  
                e.printStackTrace();  
            }  
            return ctx;  
        }  
    
        /** 
         * Método responsável por realizar a validação do login no Ldap. O campo dn 
         * é distinguished name formado anteriormente a partir da consulta do login 
         * no Ldap. 
         *  
         * @author Adriano Anderson 
         */  
        @SuppressWarnings("unchecked")
        private boolean validateUser(String dn, String senha) {  
    
            DirContext ldapCtx = null;  
            boolean bResult = false;  
    
            Hashtable env = new Hashtable();  
    
            // Especifica INITIAL CONTEXT  
            env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CTX);  
    
            // Especifica o IP/Nome e a porta do servidor LDAP  
            env.put(Context.PROVIDER_URL, SERVIDOR);  
    
            // Ldap Distingued Name  
            env.put(Context.SECURITY_PRINCIPAL, dn);  
    
            // Senha Usuário  
            env.put(Context.SECURITY_CREDENTIALS, senha);  
    
            // Tipo de Conexão  
            env.put(Context.SECURITY_AUTHENTICATION, CONNECTION_TYPE);  
    
            try {  
                // Cria um Initial Context  
                ldapCtx = new InitialDirContext(env);
    
    
            } catch (AuthenticationException auEx) {  
                System.out.println(MSG_ERROR_LDAP_VALIDATION_USER);  
                auEx.printStackTrace();  
            } catch (NamingException ne) {  
                System.out.println(MSG_ERROR_LDAP_CONNECTION);  
                ne.printStackTrace();  
            } finally {  
    
                if (ldapCtx != null) {  
                    bResult = true;  
                }  
            }  
    
            return bResult;  
        }  
    }  
    

    The class for connection testing follows:

    public class TesteLdap {
    
        public static void main(String[] args) {        
    
            Boolean autenticado = LdapAuthentication.getInstance().authentication("weles", "algumasenha");
    
            if (autenticado)
            {
                System.out.println("Autenticado");
            }
            else
            {
                System.out.println("Não Autenticado!");
            }
    
        }
    
    }
    
        
    17.09.2014 / 22:17
    1

    Hi. I know this question is old, but I was directed here because of a problem my friends were having. I created a project to authenticate and put it in the form of a library in the GitHub , which I called of Simple-LDAP.

    To use, you can do the following:

  • First include the Simple-LDAP library in your project. The best way to do this is by adding the JAR as a library. If you can not do this or you're in a hurry or something, you can even just copy and paste the ".java" files into your project, respecting the packages.

  • Then, add the class that follows. It is only necessary to configure the connection parameters properly:

    package teste;
    
    import ninja.javahacker.simpleldap.IncorrectPasswordException;
    import ninja.javahacker.simpleldap.LdapAuthenticator;
    import ninja.javahacker.simpleldap.LdapConnectionException;
    import ninja.javahacker.simpleldap.UserNotFoundException;
    
    public class Auth {
    
        private static final String LDAP_SERVER = "your.ldap.server.hostname";
        private static final int LDAP_PORT = 3268;
        private static final String ROOT_DN = "ROOT_LDAP_DN";
        private static final String ROOT_PW = "ROOT_LDAP_PASSWORD";
        private static final String DN = "dc=yourorganization,dc=example,dc=com";
    
        private static final LdapAuthenticator AUTH = createAuthenticator();
    
        private static LdapAuthenticator createAuthenticator() {
            try {
                return new LdapAuthenticator(LDAP_SERVER, LDAP_PORT, ROOT_DN, ROOT_PW, DN);
            } catch (LdapConnectionException x) {
                throw new ExceptionInInitializerError(x);
            }
        }
    
        private Auth() {}
    
        public static void authenticate(String login, String password) throws LdapConnectionException, UserNotFoundException, IncorrectPasswordException {
            AUTH.authenticate(login, password);
        }
    
        public static boolean tryAuthenticate(String login, String password) throws LdapConnectionException {
            return AUTH.tryAuthenticate(login, password);
        }
    
        public static String findUserDn(String login) throws LdapConnectionException, UserNotFoundException {
            return AUTH.findDn(login);
        }
    }
    
  • Then you can test the connection like this:

    package teste;
    
    import ninja.javahacker.simpleldap.IncorrectPasswordException;
    import ninja.javahacker.simpleldap.LdapConnectionException;
    import ninja.javahacker.simpleldap.UserNotFoundException;
    
    public class Main {
        public static void main(String[] args) throws LdapConnectionException, UserNotFoundException, IncorrectPasswordException {
            Auth.authenticate("usuario aqui", "Senha aqui");
            System.out.println("Logado com sucesso!");
        }
    }
    

    If the authentication is successful, the message will appear on the console. If it is not, the exception describing which error has occurred (connection problem, non-existent user or incorrect password) is thrown.

    Or if you prefer, do so:

    package teste;
    
    import ninja.javahacker.simpleldap.LdapConnectionException;
    
    public class Main {
        public static void main(String[] args) throws LdapConnectionException {
            System.out.println("Logado: " + Auth.tryAuthenticate("usuario aqui", "Senha aqui"));
        }
    }
    

    In this case above, the tryAuthenticate method returns true or false to tell whether authentication succeeded or not. If a connection problem occurs (and therefore does not even know if the password is correct or not), an exception is thrown.

  • 31.08.2018 / 00:04