Log in with network user (LDAP)

Asked

Viewed 3,596 times

3

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

Is there such a possibility? If yes someone knows a way for me to base myself?

2 answers

1


I have part of the solution, I hope it helps you. With the class below you can connect to 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:

  1. Validate user and password ( for this enter in it the LDAP user and password, ex: authentication("filipe","senhateste"));

  2. Validate if the user exists in LDAP (for this enter the user and password), however the password should be blank for ex: 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.

Missing find a method to find out, maybe in windows directories, if there is 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;  
    }  
}  

Follow the class for connection testing:

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!");
        }

    }

}
  • Thank you very much Weles, that’s exactly what I was going for. I will check the method to test if the user exists in ldap and as soon as possible I will be doing the tests to activate this automatic login.

  • Maraviha @Fillipe Sanches. Good luck! If you can help me with anything else let me know! Please mark the issue with more, it helps the reputation. Thank you!

  • -1 due to: (to) Campos public static without having the final (that is, global variables). (b) Malformed Javadocs. (c) Incorrect and inappropriate use of the Singleton standard. (d) Hungarian notation. (and) Improper handling of exceptions by hiding errors and polluting the System.out. (f) Methods that confuse connection error with authentication error. (g) Unjustified disregard for generic types. (h) Inappropriate use of the finally.

1

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

To use, you can do the following:

  1. First include the Simple-LDAP library in your project. The best way to do this is by adding JAR as library. If you can’t do this or are in a hurry or something, you can even just copy and paste the files ". java" from it in your project, respecting the packages.

  2. Then add the following class. You only need to configure the connection parameters accordingly:

    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);
        }
    }
    
  3. 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 authentication is successful, the message will appear on the console. If it is not, the exception describing which is the error that happened (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 method tryAuthenticate returns true or false to tell if the authentication worked or not. If a connection problem occurs (so you can’t even tell if the password is right or not), an exception is thrown.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.