IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Java Discussion :

JNDI récupération groupe d'un utilisateur AD


Sujet :

Java

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Rédacteur
    Avatar de Viduc
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Février 2009
    Messages
    1 445
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 50
    Localisation : France, Isère (Rhône Alpes)

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : Service public

    Informations forums :
    Inscription : Février 2009
    Messages : 1 445
    Billets dans le blog
    2
    Par défaut JNDI récupération groupe d'un utilisateur AD
    Bonjour

    Je souhaite récupérer les groupes d'un utilisateur sur un Active Directory mais je rencontre une erreur systématique.

    J'arrive à récupérer les infos standard (mail description etc...) mais pas les groupes.

    Je me suis appuyé sur de nombreuses aides trouvées sur le net pour faire ma class, voici ce que ça donne:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
     
        /**
         * Créer une connexion sur le serveur LDAP
         */
        public void connectLDAP()
            {
            this.environnement = new Hashtable();
            this.environnement.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
            this.environnement.put(Context.PROVIDER_URL, "ldap://"+this.getControleur()+":389");
            this.environnement.put(Context.SECURITY_AUTHENTICATION, "simple");
            this.environnement.put(Context.SECURITY_PRINCIPAL, this.getLoginDC()+","+this.getDc());
            this.environnement.put(Context.SECURITY_CREDENTIALS, this.getPasswdDC());
            try
                {this.dirContext = new InitialDirContext(this.environnement);}
            catch (NamingException e) 
                {System.out.println("Erreur lors de l'acces au serveur LDAP" + e);}
            }
     
        /**
         * Fermer la connexion au serveur LDAP
         */
        public void deconnectLDAP()
            {
            try
                {this.dirContext.close();}
            catch(NamingException e)
                {System.out.println("Erreur lors de la déconnexion du serveur LDAP" + e);}
            }
     
        public void getInfoUser(String login)
            {
            String[] group;
            C_User user = new C_User();
            user.getUser().setLogin(login);
            try
                {
                this.connectLDAP();
                Attributes attrs = dirContext.getAttributes("cn="+login+",ou=people,"+this.getDc());
                try
                    {
                    user.getUser().setDescription(attrs.get("description").get().toString());
                    System.out.println("Description : " + attrs.get("description").get());
     
                    }
                catch(NullPointerException npe)
                    {
                    user.getUser().setDescription(null);
                    System.out.println("L'utilisateur ne possède pas de description");
                    }
                try
                    {
                    user.getUser().setMail(attrs.get("mail").get().toString());
                    System.out.println("Mail : " + attrs.get("mail").get());
                    }
                catch(NullPointerException npe)
                    {
                    user.getUser().setMail(null);
                    System.out.println("L'utilisateur ne possède pas de mail");
                    }            
                try
                    {
     
                    //user.getUser().setGroupe(attrs.get("mail").get().toString());
                    //System.out.println("Mail : " + attrs.get("mail").get());
                    }
                catch(NullPointerException npe)
                    {
                    user.getUser().setMail(null);
                    System.out.println("L'utilisateur ne possède pas de mail");
                    }                          
                this.deconnectLDAP();
                }
            catch(NamingException e)
                {System.out.println("Erreur lors de la récupération d'information sur le serveur LDAP " + e);}
            this.deconnectLDAP();
            }
     
        public void getUserGroup(String login)
            {
            try 
                {
                //Create the search controls 		
                SearchControls searchCtls = new SearchControls();
     
                //Specify the search scope
                searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
     
                //specify the LDAP search filter
                String searchFilter = "(&(objectClass=user)(cn=toto))";
     
                //Specify the Base for the search
                String searchBase = this.getDc();
     
                //initialize counter to total the group members
                int totalResults = 0;
     
                //Specify the attributes to return
                String returnedAtts[]={"memberOf"};
                searchCtls.setReturningAttributes(returnedAtts);
     
                //Search for objects using the filter
                NamingEnumeration answer = this.dirContext.search(searchBase, searchFilter, searchCtls);
     
                //Loop through the search results
                while (answer.hasMoreElements()) 
                    {
                    SearchResult sr = (SearchResult)answer.next();
     
                    System.out.println(">>>" + sr.getName());
     
                    //Print out the groups
     
                    Attributes attrs = sr.getAttributes();
                    if (attrs != null) 
                        {
    				try 
                            {
                            for (NamingEnumeration ae = attrs.getAll();ae.hasMore();) 
                                {
                                Attribute attr = (Attribute)ae.next();
                                System.out.println("Attribute: " + attr.getID());
                                for (NamingEnumeration e = attr.getAll();e.hasMore();totalResults++) 
                                    {System.out.println(" " +  totalResults + ". " +  e.next());}
                                }
                            }	 
                            catch (NamingException e)	
                                {System.err.println("Problem listing membership: " + e);}
                        }
                    }
                    System.out.println("Total groups: " + totalResults);
    			this.dirContext.close();
                } 
            catch (NamingException e) 
                {System.err.println("Problem searching directory: " + e);}
            }
    j'ai cette erreur:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
     
    Exception in thread "main" java.lang.NullPointerException
    	at CONTROLEUR.C_LDAP.getUserGroup(C_LDAP.java:160)
    	at CONTROLEUR.C_Accepter_client.<init>(C_Accepter_client.java:57)
    	at Serveur.start(Serveur.java:27)
    	at Serveur.main(Serveur.java:40)
    zsh: exit 1     java Serveur
    Bien sur mon utilisateur existe bien, mon OU est la bonne, mon utilisateur pour accéder à l'AD à toute les autorisation nécessaires etc...

    J'ai essayé de faire ça:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
     
    public void getUserGroup(String user)
            {
            //Create the search controls   
            SearchControls userSearchCtls = new SearchControls();
     
            //Specify the search scope
            userSearchCtls.setSearchScope(SearchControls.OBJECT_SCOPE);
     
            //specify the LDAP search filter to find the user in question
            String userSearchFilter = "(objectClass=user)";
     
             //paceholder for an LDAP filter that will store SIDs of the groups the user belongs to
            StringBuffer groupsSearchFilter = new StringBuffer();
            groupsSearchFilter.append("(|");
     
            //Specify the Base for the search
            String userSearchBase = "CN=toto,OU=People,DC=ugr3,DC=lan";
     
            //Specify the attributes to return
            String userReturnedAtts[]={"tokenGroups"};
            userSearchCtls.setReturningAttributes(userReturnedAtts);
     
            //Search for objects using the filter
            NamingEnumeration userAnswer = null;
            try{userAnswer = this.context.search(userSearchBase, userSearchFilter, userSearchCtls);} 
            catch (NamingException ex) {Logger.getLogger(C_LDAP.class.getName()).log(Level.SEVERE, null, ex);}
     
            //Loop through the search results
            while (userAnswer.hasMoreElements()) 
                {
                SearchResult sr = null;
                try {sr = (SearchResult)userAnswer.next();} 
                catch (NamingException ex) {Logger.getLogger(C_LDAP.class.getName()).log(Level.SEVERE, null, ex);}
     
                Attributes attrs = (Attributes) sr.getAttributes();
     
                if (attrs != null) 
                    {
                    try 
                        {
                        for (NamingEnumeration ae = attrs.getAll();ae.hasMore();) 
                            {
                            Attribute attr = (Attribute)ae.next();
                            for (NamingEnumeration e = attr.getAll();e.hasMore();) 
                                {
                                byte[] sid = (byte[])e.next();
                                groupsSearchFilter.append("(objectSid=" + binarySidToStringSid(sid) + ")");
                                }
                            groupsSearchFilter.append(")");
                            }
     
                        } 
                    catch (NamingException e) {System.err.println("Problem listing membership: " + e);}
                    }
                }
            // Search for groups the user belongs to in order to get their names 
            //Create the search controls   
            SearchControls groupsSearchCtls = new SearchControls();
     
            //Specify the search scope
            groupsSearchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
     
            //Specify the Base for the search
            String groupsSearchBase = "DC=ugr3,DC=lan";
     
            //Specify the attributes to return
            String groupsReturnedAtts[]={"sAMAccountName"};
            groupsSearchCtls.setReturningAttributes(groupsReturnedAtts);
     
            //Search for objects using the filter
            NamingEnumeration groupsAnswer = null;
            try {groupsAnswer = this.context.search(groupsSearchBase, groupsSearchFilter.toString(), groupsSearchCtls);} 
            catch (NamingException ex) {Logger.getLogger(C_LDAP.class.getName()).log(Level.SEVERE, null, ex);}
     
            //Loop through the search results
            while (groupsAnswer.hasMoreElements()) 
                {
                SearchResult sr = null;
                try {sr = (SearchResult)groupsAnswer.next();} 
                catch (NamingException ex) {Logger.getLogger(C_LDAP.class.getName()).log(Level.SEVERE, null, ex);}
                Attributes attrs = sr.getAttributes();
     
                if (attrs != null) 
                    {try{System.out.println(attrs.get("sAMAccountName").get()); } 
                    catch (NamingException ex) { Logger.getLogger(C_LDAP.class.getName()).log(Level.SEVERE, null, ex);}
                    }
                }
            try {this.context.close();} 
            catch (NamingException ex) {Logger.getLogger(C_LDAP.class.getName()).log(Level.SEVERE, null, ex);}
            }
     
     
        public static final String binarySidToStringSid( byte[] SID ) 
            {
            String strSID = "";
     
            //convert the SID into string format
     
            long version;
            long authority;
            long count;
            long rid;
     
            strSID = "S";
            version = SID[0];
            strSID = strSID + "-" + Long.toString(version);
            authority = SID[4];
     
            for (int i = 0;i<4;i++) 
                {
                authority <<= 8;
                authority += SID[4+i] & 0xFF;
                }
     
            strSID = strSID + "-" + Long.toString(authority);
            count = SID[2];
            count <<= 8;
            count += SID[1] & 0xFF;
     
            for (int j=0;j<count;j++) 
                {
                rid = SID[11 + (j*4)] & 0xFF;
                for (int k=1;k<4;k++) 
                    {
                    rid <<= 8;
                    rid += SID[11-k + (j*4)] & 0xFF;
                    }
                strSID = strSID + "-" + Long.toString(rid);
                }
            return strSID;
            }
    et pareil j'obtiens:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
     
    Exception in thread "main" java.lang.NullPointerException
    	at CONTROLEUR.C_LDAP.getUserGroup(C_LDAP.java:160)
    	at CONTROLEUR.C_Accepter_client.<init>(C_Accepter_client.java:57)
    	at Serveur.start(Serveur.java:27)
    	at Serveur.main(Serveur.java:40)
    zsh: exit 1     java Serveur
    en faite ça coince au moment de la requête

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    NamingEnumeration answer = this.dirContext.search(searchBase, searchFilter, searchCtls);
    comme si il ne trouvait pas l'user ...

    d'avance merci pour toute aide

  2. #2
    Rédacteur
    Avatar de Viduc
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Février 2009
    Messages
    1 445
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 50
    Localisation : France, Isère (Rhône Alpes)

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : Service public

    Informations forums :
    Inscription : Février 2009
    Messages : 1 445
    Billets dans le blog
    2
    Par défaut


    honte a moi ... j'avais oublié de lancer mon connectLDAP()

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. [JNDI] lister les groupes d'un utilisateur
    Par mithrendil dans le forum API standards et tierces
    Réponses: 0
    Dernier message: 21/02/2012, 14h43
  2. Réponses: 1
    Dernier message: 04/04/2008, 10h32
  3. Récupération groupe utilisateur
    Par cnguyen dans le forum Shell et commandes GNU
    Réponses: 1
    Dernier message: 30/12/2007, 10h25
  4. [VB6] Recherche du groupe de l'utilisateur connecté
    Par marsup54 dans le forum VB 6 et antérieur
    Réponses: 3
    Dernier message: 02/02/2006, 14h37
  5. [LDAP] récupération login de l'utilisateur via Active Directory
    Par kcizth dans le forum Bibliothèques et frameworks
    Réponses: 6
    Dernier message: 21/12/2005, 16h47

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo