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

API standards et tierces Java Discussion :

Connexion Java / LDAP


Sujet :

API standards et tierces Java

  1. #1
    Membre régulier Avatar de dedeloux
    Profil pro
    Inscrit en
    Juillet 2005
    Messages
    104
    Détails du profil
    Informations personnelles :
    Localisation : France, Paris (Île de France)

    Informations forums :
    Inscription : Juillet 2005
    Messages : 104
    Points : 75
    Points
    75
    Par défaut Connexion Java / LDAP
    Bonjour,

    J'ai réalisé une application en java / J2EE. Je souhaiterais maintenant connecter cette application à un annuaire LDAP (Novell) en utilisant la librairie JNDI. J'aurais aimé avoir des explications concernant le fonctionnement de cette librairie.
    Est ce que j'ai besoin de configurer quelque chose pour m'en servir (je sais qu'elle est fournie avec le SDK à partir de la version 1.3 mais y a t-il autre chose que je dois savoir comme des variables à déclarer ou autre) ?
    Est ce que quelqu'un aurait un exemple simple sur lequel je pourrais m'appuyer ? Je souhaite juste me connecter et consulter des données (pas d'ajout ou de modification)
    Ensuite, je ne sais du tout dans quelle partie de mon application je dois faire ma connexion (dans la partie métier, data, domain ???)
    Enfin voilà, je ne sais pas par ou commencer. J'ai lu pas mal de documentation sur le net et sur developpez mais je n'ai pas trouver quelque chose qui m'éclaire suffissament (ou du moins je crois que je n'ai pas trop compris).
    Si quelqu'un peut me guider pas à pas dans cette démarche, ça serait très gentil.

    Toute aide sera la bienvenue !!! Merci.

  2. #2
    Membre régulier Avatar de delas
    Profil pro
    Inscrit en
    Avril 2004
    Messages
    100
    Détails du profil
    Informations personnelles :
    Localisation : France, Alpes Maritimes (Provence Alpes Côte d'Azur)

    Informations forums :
    Inscription : Avril 2004
    Messages : 100
    Points : 95
    Points
    95
    Par défaut
    Salut, tu utilises quel serveur d'application?

    ta connexion au ldap se fait sur ton serveur.

    sinon j'ai fait ca, si ca peut t'inspirer.... :
    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
     
    import javax.naming.InitialContext;
    import javax.naming.Context;
    import javax.naming.NamingEnumeration;
    import javax.naming.NamingException;
    import javax.naming.directory.Attribute;
    import javax.naming.directory.Attributes;
    import javax.naming.directory.BasicAttribute;
    import javax.naming.directory.BasicAttributes;
    import javax.naming.directory.DirContext;
    import javax.naming.directory.InitialDirContext;
    import javax.naming.directory.SearchControls;
    import javax.naming.directory.SearchResult;
     
    import javax.naming.ldap.Control;
    import javax.naming.ldap.InitialLdapContext;
    import javax.naming.ldap.LdapContext;
     
     
    	public LDAPConnexion() throws Exception{
    		//FileInputStream in = (FileInputStream) getClass().getResourceAsStream("/LDAP.properties"); 
    		in = getClass().getResourceAsStream("LDAP.properties");
    		init();
    	}
     
     
     
    	public LDAPConnexion(FileInputStream in) throws Exception{
    		this.in = in; 
    		init();
    	}
     
    	private void init() throws Exception{
    		Properties env = new Properties();
    		env.load(in);
    		in.close();
    		filtreUsr = env.getProperty("filtreUsr");
    		filtreGroups = env.getProperty("filtreGroups");
    		groupeGestion = env.getProperty("groupeGestion");
    		ctx = new InitialDirContext(env);
    		ctls = new SearchControls();
    		ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    	}
     
    	public static void main(String[] args) {
     
    		LDAPConnexion application = null;
    		try{
    			application = new LDAPConnexion();
    		}catch (Exception e) {
    				e.printStackTrace();
    		}
    		Attributes a = application.getAttributes("monuser");
    		application.printAll(a);
    }
     
    	private Attributes getAttributes(String login){
    		NamingEnumeration namingEnumeration = getNamingEnumeration("SAMAccountName="+login,"ou="+filtreUsr);
    	//	NamingEnumeration namingEnumeration = getNamingEnumeration("SAMAccountName="+login,"ou=Banking_Users");
    		if (namingEnumeration == null){
    			return null;
    		}else{
    			try{
    				if (! namingEnumeration.hasMore()){
    	//				System.out.println("! namingEnumeration.hasMoreElements()");
    				}
    			}catch(Exception e){
    				e.printStackTrace();
    				return null;
    			}
    		}
    		SearchResult searchResult = (SearchResult) namingEnumeration.nextElement();
    		if (searchResult == null){
    			return null;
    		}
    		return searchResult.getAttributes();//+filtreUsr
    	}
     
    }
    	private void printAll(Attributes usr){
    		Enumeration e = usr.getAll();
    		while (e.hasMoreElements()) {
    			String element = e.nextElement().toString();
    		}
    	}
    }
    voilou... n'hesite pas a me demander si t'as des soucis...

  3. #3
    Membre régulier Avatar de dedeloux
    Profil pro
    Inscrit en
    Juillet 2005
    Messages
    104
    Détails du profil
    Informations personnelles :
    Localisation : France, Paris (Île de France)

    Informations forums :
    Inscription : Juillet 2005
    Messages : 104
    Points : 75
    Points
    75
    Par défaut
    Bonjour,
    merci de ta réponse !!!

    En ce qui concerne le serveur d'application j'utilise Tomcat.
    Je ne souhaite faire ma connexion sur mon serveur mais plutot l'initialiser dans mon appli un peu comme une connexion à Oracle. Est ce que c'est possible de faire ça ?
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
    		<property name="jndiName" value="${jndi.jdbc.egesco}" />
    	</bean>
    Bien sur je précise aussi l'url, le user et le mot de passe. Qu'est ce que tu en penses ?

    Admettons que je fais comme ça pour ma connexion et que ça marche . Qu'est ce que je dois faire ensuite ? Est ce que je peux ajouter une requete dans une classe déjà existante en important les classes jndi ?
    Pour l'instant j'ai cette classe là :
    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
     
    public class JdbcLdapUserDao extends JdbcDaoSupport implements LdapUserDao {
     
     private static final String BASE_SQL_LIST_LDAPUSERS_QUERY = "SELECT cn, lastname, firstname FROM t_adm_ldap WHERE cn NOT IN (SELECT cn FROM t_adm_utilisateur)ORDER BY cn";
    private static class LdapUserRowMapper implements RowMapper{
    public Object mapRow(ResultSet pResultSet, int pRowNum) throws SQLException {
     
    			LdapUser ldapUser = new LdapUser();
    			ldapUser.setCommonName(pResultSet.getString("cn"));
    			ldapUser.setLastName(pResultSet.getString("lastname"));
    			ldapUser.setFirstName(pResultSet.getString("firstname"));
     
    			return ldapUser;
    		}
    public JdbcLdapUserDao() {
            super();
        }
    public List listLdapUser() {
    		List ldapUsers = null;
    		ldapUsers = JdbcDaoUtils.listObjects(getJdbcTemplate(),BASE_SQL_LIST_LDAPUSERS_QUERY, null,new LdapUserRowMapper());
    		return ldapUsers;
    	}
    }
    Bon pour l'instant je vais chercher mes user dans une base oracle mais je veux maintenant aller les chercher dans mon annuaire .
    Est ce que tu pourrais me dire ce que je dois modifier ou comment je dois m'y prendre .

    Merci pour ta patience !!!

  4. #4
    Membre régulier Avatar de delas
    Profil pro
    Inscrit en
    Avril 2004
    Messages
    100
    Détails du profil
    Informations personnelles :
    Localisation : France, Alpes Maritimes (Provence Alpes Côte d'Azur)

    Informations forums :
    Inscription : Avril 2004
    Messages : 100
    Points : 95
    Points
    95
    Par défaut
    tu peux faire une connexion a ton ldap pour recuperer des données sur une personne.

    c'est ce que je fais dans mon init :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    
    	private void init() throws Exception{
    		Properties env = new Properties();
    		env.load(in);
    		in.close();
    		filtreUsr = env.getProperty("filtreUsr");
    		filtreGroups = env.getProperty("filtreGroups");
    		groupeGestion = env.getProperty("groupeGestion");
    		ctx = new InitialDirContext(env);		ctls = new SearchControls();
    		ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    	}
    mais je ne penses pas que tu puisse recuperer le user et pwd pour connecter un gars...

  5. #5
    Membre du Club
    Inscrit en
    Janvier 2005
    Messages
    38
    Détails du profil
    Informations personnelles :
    Âge : 42

    Informations forums :
    Inscription : Janvier 2005
    Messages : 38
    Points : 46
    Points
    46
    Par défaut
    Moi j'ai un peu exemple de gestion en java du LDAP active directory si ca peut aider:

    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
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
     
    // ADConnection - A Java class that encapsulates a JNDI connection to 
    // an Active Directory
    //
    // Written by Jeremy E. Mortis  mortis@ucalgary.ca  2002-07-03 
    //
    // Note that password changes require an SSL connection to the Active Directory,
    // but other types of calls do not.
    //
    // To set up the SSL connection, check out:
    //    http://java.sun.com/j2se/1.3/docs/tooldocs/win32/keytool.html
    //    http://www.microsoft.com/windows2000/techinfo/planning/security/casetupsteps.asp
     
    package it.service;
     
    import javax.swing.*;
    import java.awt.*;
    import javax.naming.*;
    import javax.naming.directory.*;
    import javax.naming.ldap.*;
    import java.util.*;
    import java.security.*;
     
    public class ADConnection {
     
      DirContext ldapContext;
      String baseName = ",cn=users,DC=activedirectory,DC=myorg,DC=ca";
      String serverIP = "activedirectory.myorg.ca";
      String modelUsername = "template";
     
      public ADConnection() {
        try {
          Hashtable ldapEnv = new Hashtable(11);
          ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
          ldapEnv.put(Context.PROVIDER_URL,  "ldap://" + serverIP + ":636");
          ldapEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
          ldapEnv.put(Context.SECURITY_PRINCIPAL, "cn=ldapadmin" + baseName);
          ldapEnv.put(Context.SECURITY_CREDENTIALS, "xxxx");
          ldapEnv.put(Context.SECURITY_PROTOCOL, "ssl");
          ldapContext = new InitialDirContext(ldapEnv);
          }
          catch (Exception e) {
            System.out.println(" bind error: " + e);
            e.printStackTrace();
            System.exit(-1);
         }
      }
     
      public void createNew(String username, String surname, String givenName) {
        try {
          String distinguishedName = "cn=" + username + baseName;
          Attributes newAttributes = new BasicAttributes(true);
          Attribute oc = new BasicAttribute("objectclass");
          oc.add("top");
          oc.add("person");
          oc.add("organizationalperson");
          oc.add("user");
          newAttributes.put(oc);
          newAttributes.put(new BasicAttribute("sAMAccountName", username));
          newAttributes.put(new BasicAttribute("userPrincipalName", username + "@" + serverIP));
          newAttributes.put(new BasicAttribute("cn", username));
          newAttributes.put(new BasicAttribute("sn", surname));
          newAttributes.put(new BasicAttribute("givenName", givenName));
          newAttributes.put(new BasicAttribute("displayName", givenName + " " + surname));
          System.out.println("Name: " + name + " Attributes: " + a);
          ldapContext.createSubcontext(distinguishedName, newAttributes);
        }
        catch (Exception e) {
          System.out.println("create error: " + e);
          e.printStackTrace();
          System.exit(-1);
        }
      }
     
      public void createClone(String username, String surname, String givenName) {
        try {
          Attributes modelAttributes = fetch(modelUsername);
          String distinguishedName = "cn=" + username + baseName;
          Attributes newAttributes = new BasicAttributes(true);
          newAttributes.put(modelAttributes.get("objectclass"));
          newAttributes.put(modelAttributes.get("userAccountControl"));
          newAttributes.put(new BasicAttribute("sAMAccountName", username));
          newAttributes.put(new BasicAttribute("userPrincipalName", username + "@" + serverIP));
          newAttributes.put(new BasicAttribute("cn", username));
          newAttributes.put(new BasicAttribute("sn", surname));
          newAttributes.put(new BasicAttribute("givenName", givenName));
          newAttributes.put(new BasicAttribute("displayName", givenName + " " + surname));
          System.out.println("distinguishedName: " + distinguishedName + " Attributes: " + newAttributes);
          ldapContext.createSubcontext(distinguishedName, newAttributes);
        }
        catch (Exception e) {
          System.out.println("create clone error: " + e);
          e.printStackTrace();
          System.exit(-1);
        }
      }
     
      public void update(String username) {
        try {
          System.out.println("updating...\n");
          ModificationItem[] mods = new ModificationItem[1];
          mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
            new BasicAttribute("description", "java y"));
          ldapContext.modifyAttributes("cn=" + username + baseName, mods);
         }
          catch (Exception e) {
            System.out.println(" update error: " + e);
            System.exit(-1);
          }
      }
     
     
      public void updatePassword(String username, String password) {
        try {
          System.out.println("updating password...\n");
          String quotedPassword = "\"" + password + "\"";
          char unicodePwd[] = quotedPassword.toCharArray();
          byte pwdArray[] = new byte[unicodePwd.length * 2];
          for (int i=0; i<unicodePwd.length; i++) {
            pwdArray[i*2 + 1] = (byte) (unicodePwd[i] >>> 8);
            pwdArray[i*2 + 0] = (byte) (unicodePwd[i] & 0xff);
          }
          System.out.print("encoded password: ");
          for (int i=0; i<pwdArray.length; i++) {
            System.out.print(pwdArray[i] + " ");
          }
          System.out.println();
          ModificationItem[] mods = new ModificationItem[1];
          mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
            new BasicAttribute("UnicodePwd", pwdArray));
          ldapContext.modifyAttributes("cn=" + username + baseName, mods);
         }
          catch (Exception e) {
            System.out.println("update password error: " + e);
            System.exit(-1);
          }
      }
     
      public Attributes fetch(String username) {
        Attributes attributes = null;
        try {
          System.out.println("fetching: " + username);
          DirContext o = (DirContext)ldapContext.lookup("cn=" + username + baseName);
          System.out.println("search done\n");
          attributes = o.getAttributes("");
          for (NamingEnumeration ae = attributes.getAll(); ae.hasMoreElements();) {
            Attribute attr = (Attribute)ae.next();
            String attrId = attr.getID();
            for (NamingEnumeration vals = attr.getAll(); vals.hasMore();) {
              String thing = vals.next().toString();
              System.out.println(attrId + ": " + thing);
            }
          }
        }
        catch (Exception e) {
          System.out.println(" fetch error: " + e);
          System.exit(-1);
        }
        return attributes;
      }
     
      public static void main(String[] args) {
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        // the keystore that holds trusted root certificates
        System.setProperty("javax.net.ssl.trustStore", "e:\\ldap\\keystore");
        System.setProperty("javax.net.debug", "all");
        ADConnection adc = new ADConnection();
        adc.createClone("clone1", "Clone", "Clarissa");
        adc.updatePassword("clone1", "xxxx");
        adc.createNew("user1, "User", "Joe");
        Attributes a = adc.fetch("clone1");
      }

  6. #6
    Membre du Club
    Inscrit en
    Janvier 2005
    Messages
    38
    Détails du profil
    Informations personnelles :
    Âge : 42

    Informations forums :
    Inscription : Janvier 2005
    Messages : 38
    Points : 46
    Points
    46
    Par défaut
    Le mieux qu'en tu utilise OpenLDAP ou novell c'est d'utilisé la libraire jldap de novel, elle marche trés bien avec OpenLDAP

    tu trouvera la librairie ici: http://developer.novell.com/wiki/index.php/Jldap

    et des exemple d'utilisation ici: http://www.openldap.org/jldap/overview.html

  7. #7
    Membre régulier Avatar de dedeloux
    Profil pro
    Inscrit en
    Juillet 2005
    Messages
    104
    Détails du profil
    Informations personnelles :
    Localisation : France, Paris (Île de France)

    Informations forums :
    Inscription : Juillet 2005
    Messages : 104
    Points : 75
    Points
    75
    Par défaut
    OK !!
    Merci pour vos réponses, je vais me renseigner sur jldap et je vous tiens au courant.

  8. #8
    Membre régulier Avatar de silverfab34
    Inscrit en
    Mars 2006
    Messages
    203
    Détails du profil
    Informations personnelles :
    Âge : 44

    Informations forums :
    Inscription : Mars 2006
    Messages : 203
    Points : 91
    Points
    91
    Par défaut
    Citation Envoyé par BriceTheNice Voir le message
    Moi j'ai un peu exemple de gestion en java du LDAP active directory si ca peut aider:

    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
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
     
    // ADConnection - A Java class that encapsulates a JNDI connection to 
    // an Active Directory
    //
    // Written by Jeremy E. Mortis  mortis@ucalgary.ca  2002-07-03 
    //
    // Note that password changes require an SSL connection to the Active Directory,
    // but other types of calls do not.
    //
    // To set up the SSL connection, check out:
    //    http://java.sun.com/j2se/1.3/docs/tooldocs/win32/keytool.html
    //    http://www.microsoft.com/windows2000/techinfo/planning/security/casetupsteps.asp
     
    package it.service;
     
    import javax.swing.*;
    import java.awt.*;
    import javax.naming.*;
    import javax.naming.directory.*;
    import javax.naming.ldap.*;
    import java.util.*;
    import java.security.*;
     
    public class ADConnection {
     
      DirContext ldapContext;
      String baseName = ",cn=users,DC=activedirectory,DC=myorg,DC=ca";
      String serverIP = "activedirectory.myorg.ca";
      String modelUsername = "template";
     
      public ADConnection() {
        try {
          Hashtable ldapEnv = new Hashtable(11);
          ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
          ldapEnv.put(Context.PROVIDER_URL,  "ldap://" + serverIP + ":636");
          ldapEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
          ldapEnv.put(Context.SECURITY_PRINCIPAL, "cn=ldapadmin" + baseName);
          ldapEnv.put(Context.SECURITY_CREDENTIALS, "xxxx");
          ldapEnv.put(Context.SECURITY_PROTOCOL, "ssl");
          ldapContext = new InitialDirContext(ldapEnv);
          }
          catch (Exception e) {
            System.out.println(" bind error: " + e);
            e.printStackTrace();
            System.exit(-1);
         }
      }
     
      public void createNew(String username, String surname, String givenName) {
        try {
          String distinguishedName = "cn=" + username + baseName;
          Attributes newAttributes = new BasicAttributes(true);
          Attribute oc = new BasicAttribute("objectclass");
          oc.add("top");
          oc.add("person");
          oc.add("organizationalperson");
          oc.add("user");
          newAttributes.put(oc);
          newAttributes.put(new BasicAttribute("sAMAccountName", username));
          newAttributes.put(new BasicAttribute("userPrincipalName", username + "@" + serverIP));
          newAttributes.put(new BasicAttribute("cn", username));
          newAttributes.put(new BasicAttribute("sn", surname));
          newAttributes.put(new BasicAttribute("givenName", givenName));
          newAttributes.put(new BasicAttribute("displayName", givenName + " " + surname));
          System.out.println("Name: " + name + " Attributes: " + a);
          ldapContext.createSubcontext(distinguishedName, newAttributes);
        }
        catch (Exception e) {
          System.out.println("create error: " + e);
          e.printStackTrace();
          System.exit(-1);
        }
      }
     
      public void createClone(String username, String surname, String givenName) {
        try {
          Attributes modelAttributes = fetch(modelUsername);
          String distinguishedName = "cn=" + username + baseName;
          Attributes newAttributes = new BasicAttributes(true);
          newAttributes.put(modelAttributes.get("objectclass"));
          newAttributes.put(modelAttributes.get("userAccountControl"));
          newAttributes.put(new BasicAttribute("sAMAccountName", username));
          newAttributes.put(new BasicAttribute("userPrincipalName", username + "@" + serverIP));
          newAttributes.put(new BasicAttribute("cn", username));
          newAttributes.put(new BasicAttribute("sn", surname));
          newAttributes.put(new BasicAttribute("givenName", givenName));
          newAttributes.put(new BasicAttribute("displayName", givenName + " " + surname));
          System.out.println("distinguishedName: " + distinguishedName + " Attributes: " + newAttributes);
          ldapContext.createSubcontext(distinguishedName, newAttributes);
        }
        catch (Exception e) {
          System.out.println("create clone error: " + e);
          e.printStackTrace();
          System.exit(-1);
        }
      }
     
      public void update(String username) {
        try {
          System.out.println("updating...\n");
          ModificationItem[] mods = new ModificationItem[1];
          mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
            new BasicAttribute("description", "java y"));
          ldapContext.modifyAttributes("cn=" + username + baseName, mods);
         }
          catch (Exception e) {
            System.out.println(" update error: " + e);
            System.exit(-1);
          }
      }
     
     
      public void updatePassword(String username, String password) {
        try {
          System.out.println("updating password...\n");
          String quotedPassword = "\"" + password + "\"";
          char unicodePwd[] = quotedPassword.toCharArray();
          byte pwdArray[] = new byte[unicodePwd.length * 2];
          for (int i=0; i<unicodePwd.length; i++) {
            pwdArray[i*2 + 1] = (byte) (unicodePwd[i] >>> 8);
            pwdArray[i*2 + 0] = (byte) (unicodePwd[i] & 0xff);
          }
          System.out.print("encoded password: ");
          for (int i=0; i<pwdArray.length; i++) {
            System.out.print(pwdArray[i] + " ");
          }
          System.out.println();
          ModificationItem[] mods = new ModificationItem[1];
          mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
            new BasicAttribute("UnicodePwd", pwdArray));
          ldapContext.modifyAttributes("cn=" + username + baseName, mods);
         }
          catch (Exception e) {
            System.out.println("update password error: " + e);
            System.exit(-1);
          }
      }
     
      public Attributes fetch(String username) {
        Attributes attributes = null;
        try {
          System.out.println("fetching: " + username);
          DirContext o = (DirContext)ldapContext.lookup("cn=" + username + baseName);
          System.out.println("search done\n");
          attributes = o.getAttributes("");
          for (NamingEnumeration ae = attributes.getAll(); ae.hasMoreElements();) {
            Attribute attr = (Attribute)ae.next();
            String attrId = attr.getID();
            for (NamingEnumeration vals = attr.getAll(); vals.hasMore();) {
              String thing = vals.next().toString();
              System.out.println(attrId + ": " + thing);
            }
          }
        }
        catch (Exception e) {
          System.out.println(" fetch error: " + e);
          System.exit(-1);
        }
        return attributes;
      }
     
      public static void main(String[] args) {
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        // the keystore that holds trusted root certificates
        System.setProperty("javax.net.ssl.trustStore", "e:\\ldap\\keystore");
        System.setProperty("javax.net.debug", "all");
        ADConnection adc = new ADConnection();
        adc.createClone("clone1", "Clone", "Clarissa");
        adc.updatePassword("clone1", "xxxx");
        adc.createNew("user1, "User", "Joe");
        Attributes a = adc.fetch("clone1");
      }

    Bonjour,
    J'ai vu cotre code et il est tres interessant !
    Par contre, j'ai une question (je debute en LDAP et jndi)........si avant des creer un utilisateur, on veut verifier qu'il n'existe pas deja dans l'annuaire, comment fais ton ?
    Merci pour votre aide !

  9. #9
    Membre à l'essai
    Homme Profil pro
    Étudiant
    Inscrit en
    Avril 2011
    Messages
    78
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Étudiant
    Secteur : Industrie

    Informations forums :
    Inscription : Avril 2011
    Messages : 78
    Points : 18
    Points
    18
    Par défaut Annuaire LDAP
    Bonjour,

    j'ai un petit souci c'est pour cela que je me tourne vers vous, en faite je dois effectuer une ihm permettant de prendre des informations dans un annuaire ldap pour les copier vers un autre annuaire, pour le moment j'ai réussi la connexion a l'annuaire qui me permet par la suite d'effectuer une recherche et une récupération j'ai fait aussi sur cette page une fonction copier qui permet avec les élément récupérer de pouvoir les copier vers un autre annuaire ldap mais j'obtiens l'erreur 68 de ldap et si j'ai bien compris il me dise en gros que l'utilisateur que je veux copier existe déjà dans l'annuaire du coup je ne comprend pas car ce user n'existe pas dedans

    Merci pour vos aides

Discussions similaires

  1. [JAVA-LDAP] Connexion LDAP JNDI
    Par shaun_the_sheep dans le forum Général Java
    Réponses: 1
    Dernier message: 06/06/2013, 08h41
  2. Pblm Connexion Java - LDAP (active directory)
    Par silverfab34 dans le forum Général Java
    Réponses: 15
    Dernier message: 15/05/2008, 16h17
  3. Connexion Java - LDAP
    Par silverfab34 dans le forum API standards et tierces
    Réponses: 1
    Dernier message: 04/03/2008, 10h33
  4. connexion a ldap avec java
    Par himachalene dans le forum API standards et tierces
    Réponses: 4
    Dernier message: 05/12/2006, 19h15
  5. [VB.Net][2.0] Connexion à LDAP
    Par Bz dans le forum ASP.NET
    Réponses: 3
    Dernier message: 14/12/2005, 11h57

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