Java: Pega Grupos do Usuario no LDAP

From Wiki
Revision as of 22:39, 25 September 2014 by Ebasso (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Essa classe conecta a um servidor LDAP e busca os grupos que usuário pertence, logo depois busca o atributo name do grupo respectivo

Solução testada usando o IBM Tivoli Directory Server

Os pré-requisitos são

  • Dados para conexão ao servidor ldap

Código

Código abaixo.

import javax.naming.*; 
import javax.naming.directory.*; 
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Enumeration;
import java.util.Hashtable; 
import java.util.Properties; 

/**
* Solução testada com o Tivoli Directory Server
* @author ebasso
*
*/
public class PegaGruposUsuario {
   
	public static final String _IBM_ALL_GROUPS_ = "ibm-allGroups";
	public static final String _AD_MEMBER_OF = "MemberOf";
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {

		try {
			PrintStream out = System.out;
			Properties pconn = new Properties();
			
			
 			PegaGruposUsuario jlquery = new PegaGruposUsuario();
			// Dev
	    	pconn.setProperty("ldap.URL", "ldap://192.168.10.1:389/"); 
	    	pconn.setProperty("ldap.BaseDN", "O=EMPRESAX,C=BR"); 
	    	pconn.setProperty("ldap.user","uid=UsuarioBind,ou=usuarios,o=empresax,c=br"); 
	    	pconn.setProperty("ldap.password", "password");
	    	
	    	String commonName = "Fulano de Tak";
			jlquery.runSolucao(out,pconn,commonName); 
			
 		
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
 		
	public void runSolucao(PrintStream out, Properties ldapconn, String userName) throws Exception {
			
		if ((userName == null) || (userName.equals(""))){
		    printNoGroup(out);
		    return;
		}
		userName = userName+"*";
		
		ArrayList<String> userGroups = buscaGruposUsuario(ldapconn, userName);
		
		if (userGroups == null ) {  // usuário não cadastrado em grupos
			printNoGroup(out);
			return ;
		} 
		
		ArrayList<String[]> arrayGruposLDAP = buscaNomeGrupo(ldapconn, userGroups);
		if ( arrayGruposLDAP == null) { // nenhuma grupo tem caixa postal corporativa
			printNoName(out);
			return ;
		}
		
		// Pega os resultados e monta Retorno
		printRetorno(out, arrayGruposLDAP);
	}

	private ArrayList<String> buscaGruposUsuario (Properties ldapconn, String userName) throws Exception{
	
		String filter = "(&(objectClass=person)(uid=" + userName + "))";
		String[] attrIDs = {_IBM_ALL_GROUPS_};
			
		NamingEnumeration result = executaLdapQuery(ldapconn,filter,attrIDs);
		   	
    	ArrayList<String> userGroups = null;
       if (result.hasMore()) {
        	userGroups = new ArrayList<String>();
	    	while (result.hasMore()) {
	        	SearchResult sr = (SearchResult)result.next();                     		
	        	System.out.println("1>>>" + sr.toString());
	        	Attributes attrs = sr.getAttributes();
	        	
	        	for ( Enumeration e1 = attrs.get(_IBM_ALL_GROUPS_).getAll() ; e1.hasMoreElements() ; ) {
	                String dnGroup = e1.nextElement().toString();
	                
 	                userGroups.add(dnGroup);
 	                //System.out.println("dnGroup>" + dnGroup);
	        	}   
 	            break;      
	        }
         }        	
         
         ldapconn.setProperty("filter","");
 		return userGroups;
	}
 
	private ArrayList<String[]> buscaNomeGrupo (Properties ldapconn, ArrayList<String> userGroups) throws  
Exception { 
		
		//String[] attrIDs = {"*"};
		String[] attrIDs = {"name"};
		
				
		ArrayList<String[]> arrayAUX = null;
		
		Iterator itr = userGroups.iterator();
	    while (itr.hasNext()){
	    	String groupName = (String) itr.next();
	    	groupName =  this.getCN(groupName);
	    	//System.out.println("=>" + groupName);
	    	String filter = "(&(objectClass=groupOfUniqueNames)(cn="+ groupName + "))";

	    	NamingEnumeration result = executaLdapQuery(ldapconn,filter,attrIDs);
	    	while (result.hasMore()) {
	        	SearchResult sr = (SearchResult)result.next();        
	        	System.out.println("Z>>>" +sr.toString());
	        	String[] sAux = this.getGroupAttributes(sr.getAttributes());
	        	if (sAux != null) {
	        		if (arrayAUX == null) {
	        			arrayAUX = new ArrayList<String[]>();
	        		}
 	        		arrayAUX.add(sAux);
	        	}
	        	
	    	}
	    }
	    ldapconn.setProperty("filter","");
		return arrayAUX;
	}
	
	private NamingEnumeration executaLdapQuery(Properties ldapquery,String filter,String[] attrIDs) throws 
Exception {
		 // Set up the environment for creating the initial context 
       String ldapCF = "com.sun.jndi.ldap.LdapCtxFactory"; 
       String ldapURL = ldapquery.getProperty("ldap.URL"); 
       String ldapBaseDN = ldapquery.getProperty("ldap.BaseDN"); 
        String ldapUserID = ldapquery.getProperty("ldap.user");
       String ldapPassword = ldapquery.getProperty("ldap.password");  
      
       Hashtable env = new Hashtable(5); 
      env.put(Context.INITIAL_CONTEXT_FACTORY, ldapCF); 
      env.put(Context.PROVIDER_URL, ldapURL + ldapBaseDN); 
      env.put(Context.SECURITY_PRINCIPAL, ldapUserID); 
       env.put(Context.SECURITY_CREDENTIALS, ldapPassword); 
     //set security credentials, note using simple cleartext authentication
		env.put(Context.SECURITY_AUTHENTICATION,"simple");
             	
      // Create initial context 
      DirContext ctx = new InitialDirContext(env); 
   
      SearchControls ctls = new SearchControls(); 
      ctls.setReturningAttributes(attrIDs);
      ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
          
      // Search for objects using the above filter 
      NamingEnumeration result = ctx.search("", filter, ctls); 
    					
      // Close the context when we're done 
      ctx.close();
      return result;
	}
	     
   private void printRetorno(PrintStream out, ArrayList<String[]> arrayAUX) {

       String xOut = "";
 	    	
       Iterator itr = arrayAUX.iterator();
	    while (itr.hasNext()){
	    	String[] sDado = (String[]) itr.next();
	    
	    	xOut =  "N>> [" + sDado[0] + "]";
	    	out.println(xOut);
	    }
   }
	     
   private void printNoGroup(PrintStream out) {
       String xOut = "Usuário não está dentro de Grupos";
   	
   	out.println(xOut);
   }
   
       
   private void printNoName(PrintStream out) {
       String xOut = "Sem Nome Populados";
   	
   	out.println(xOut);
   }
   	
   public static String getCN(String aux) {
   	
       if (aux != null && aux.toUpperCase().startsWith("CN=")) {
       	aux = aux.substring(3).trim();
       }
       int position = aux.indexOf(',');
       if (position == -1) {
           return aux;
       } else {
           return aux.substring(0, position);
       }
   }

   private String[] getGroupAttributes(Attributes attrs) {	
   	String aux3 = "";
   	
   	Attribute attr3 = attrs.get("name");
   	
   	if (attr3 != null) {
   		aux3 = attr3.toString();
   		
   		if (aux3.toUpperCase().startsWith("NAME:")) {
       		aux3 = aux3.substring(5).trim();
   		}
   	}	
       return (new String[] {aux3});
   }
    	
}


Ver também