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

Langage Java Discussion :

[LDAP / Java] Utiliser les objetclass comme filtre


Sujet :

Langage Java

  1. #1
    Membre à l'essai
    Profil pro
    Inscrit en
    Juin 2010
    Messages
    25
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juin 2010
    Messages : 25
    Points : 19
    Points
    19
    Par défaut [LDAP / Java] Utiliser les objetclass comme filtre
    Bonjour,

    J'ai codé une fonction java lors de mes premières semaines de taf en janvier pour se connecter au LDAP de ma boite et récupérer un User. Afin de vérifier si les données dans la base étaient égales aux données du ldap.

    Cette fonction renvoie une chaine de string. Mon boss veut maintenant que je rajoute des critères de recherche via les objetclass.. Et la je sèche. Je pensait que le meilleur moyen était de rajouter un paramètre à intégrer dans l'user interne. Mais rien ne marche. Je ne sais pas ou mettre ce Where. Car à priori les filtre de recherche par objetclass correspondent au where du SQL.

    Y pas mal de doc sur internet.. mais aucune précise techniquement, l'un de vous serait déjà tombé sur ce problème ? ou faut il caser ces fameux objetclass ?

    La syntaxe devrait a priori ressembler a cet exemple sur le net mais... La je sèche.
    (&(objectclass=person)(telephoneNumber=*))

    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
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    import java.nio.charset.Charset;
    import java.security.MessageDigest;
    import java.security.NoSuchAlgorithmException;
    import java.util.Hashtable;
     
    import javax.naming.Context;
    import javax.naming.NamingException;
    import javax.naming.directory.Attributes;
    import javax.naming.directory.DirContext;
    import javax.naming.directory.InitialDirContext;
     
    import sun.misc.BASE64Encoder;
     
    // @Importer library
     
    public class ConnexionLDAP3 {
     
     
    	public static void main(String[] args) {
     
    		String adresseServLDAP = "ADRESSELDAP";
    		String portServLDAP = "PORT";
    		String userInterneLDAP = "UserInterne";
    		String mdpUserInterneLDAP = "mdpuserinterne";
    		String userData = "userdata";
    		String mdpData = "mdpuserdata";
     
    		ConnectLDAP(adresseServLDAP, portServLDAP, userInterneLDAP,
    				mdpUserInterneLDAP, userData, mdpData);
    	}
     
     
    	public static String ConnectLDAP(String adresseServLDAP,
    			String portServLDAP, String userInterneLDAP,
    			String mdpUserInterneLDAP, String userData, String mdpData)
    	{
    		String retour ="nothing";
     
    		// Connexion - Authentification LDAP
    		Hashtable environnement = new Hashtable();
    		environnement.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    		environnement.put(Context.PROVIDER_URL, "ldap://" + adresseServLDAP+ ":" + portServLDAP + "/");
    		environnement.put(Context.SECURITY_AUTHENTICATION, "simple");
    		environnement.put(Context.SECURITY_PRINCIPAL, userInterneLDAP);
    		environnement.put(Context.SECURITY_CREDENTIALS, mdpUserInterneLDAP);		
    		BASE64Encoder enc = new BASE64Encoder();
    		MessageDigest digest = null;
     
    		try {
     
    			// On appelle le contexte à partir de l'environnement
    			DirContext contexte = new InitialDirContext(environnement);
    			System.out.println("Connexion au serveur : SUCCES");
     
    			try {
     
    				// On recupere les attributs
    				Attributes attrs = contexte.getAttributes(userInterneLDAP);
    				System.out.println("Recupération des attributs : SUCCES");
     
    				// Recup Login
    				String userFinded = attrs.get("objectClass").toString();
    				System.out.println(userFinded);
    				stringtotable(userFinded);
     
    				// Recupération password LDAP
    				byte[] bb = (byte[]) (attrs.get("userPassword").get());
    				String lStringLDAP = new String(bb, Charset.forName("UTF8"));
     
    				//	System.out.println("Donnée LDAP :");
    				System.out.println("Donnée mdp reçu LDAP :  "+lStringLDAP);
     
    				// parsage du login
    				userFinded = smartCutData(userFinded, "givenName");
     
    				try{
    					String pass = base64(md5(mdpData));
    					String lStringData = encode(mdpData, "MD5");
    					System.out.println(lStringData);
    					byte [] byteData = lStringData.getBytes();
    					lStringData = base64(byteData);
    					System.out.println("pass "+pass);
    				}
    					catch (Exception e){	
    				}
     
    				// Check validité authentification
    				retour = checkIds(userData, userFinded, mdpData,"sneacke");
     
    				if (retour == "OK") {
     
    					retour = retour + "/";
    					// traitement
     
    					//fin de retour double dash
    					retour = retour + "/";
    				}
     
    			} catch (NamingException e) {
    				System.out.println("Recuperation ECHEC");
    				e.printStackTrace();
    				retour = "erreur parametrage";
    			}
    		} catch (NamingException e) {
    			System.out.println("Connexion au serveur : ECHEC");
    			retour = "impossible de se connecter au LDAP";
    			e.printStackTrace();
    		}
    		System.out.println(retour);
    		return retour;
    	}
     
     
    	public static String CheckValue (String ldapValue, String dataValue, String returnValue) {
     
    		if ( ldapValue != dataValue){
    			if (returnValue == "Ok"){ returnValue = "Ok/";};
    			returnValue = returnValue + ldapValue + "/";
    		}
    		return returnValue;
    	}
     
    	private static String smartCutData(String value, String attribute) {
     
    		String cutValue;
    		cutValue = "Undefined";
     
    		if (attribute == "givenName") {
    			cutValue = value.substring(11);
    		}
    		if (attribute == "userPassword") {
    			cutValue = value.substring(14);
    		}
    		return cutValue;
    	}
     
    	private static String checkIds(String loginData, String loginLDAP,
    			String mdpData, String mdpLDAP) {
     
    		String cutValue;
    		cutValue = "Undefined";
     
    		if (loginData.equals(loginLDAP)) {
    			cutValue = "Login connu";
    		} else {
     
    			System.out.println("Login inconnu");
    			cutValue = "Login inconnu";
    		}
     
    		if (cutValue == "Login connu") {
    			if (mdpData == mdpLDAP) {
    				cutValue = "OK";
    				System.out.println("Login & Mot de passe : SUCCES");
    			} else {
    				cutValue = "Mdp Incorrect";
    				System.out.println("Mdp incorrect");
    			}
    		}
    		return cutValue;
    	}
     
    	public static String base64(byte[] bytes) {
    		return "{MD5}" + new sun.misc.BASE64Encoder().encode(bytes);
     
    	}
     
    	private static String encode(String password, String algorithm) {
    		byte[] hash = null;
    		try {
    			MessageDigest md = MessageDigest.getInstance(algorithm);
    			hash = md.digest(password.getBytes());
    		} catch (NoSuchAlgorithmException e) {
    			e.printStackTrace();
    		}
    		StringBuilder sb = new StringBuilder();
    		for (int i = 0; i < hash.length; ++i) {
    			String hex = Integer.toHexString(hash[i]);
    			if (hex.length() == 1) {
    				sb.append(0);
    				sb.append(hex.charAt(hex.length() - 1));
    			} else {
    				sb.append(hex.substring(hex.length() - 2));
    			}
    		}
    		return sb.toString();
    	}
    	public static byte[] md5(String text) throws Exception {
    		MessageDigest md = MessageDigest.getInstance("MD5");
    		return md.digest(text.getBytes("utf-8"));
    	}
     
    	/*
    	 * Function convertissant les string en table 
    	 * Les strings doivent etre séparé par une virgule
    	 */
    	public static Object[] stringtotable(String chaineString) {
     
    		String[] splitArray = null; 
    		splitArray = chaineString.split(",");
    		return splitArray;
    	}
    }

  2. #2
    Membre confirmé Avatar de Mobius
    Profil pro
    none
    Inscrit en
    Avril 2005
    Messages
    463
    Détails du profil
    Informations personnelles :
    Localisation : France, Isère (Rhône Alpes)

    Informations professionnelles :
    Activité : none

    Informations forums :
    Inscription : Avril 2005
    Messages : 463
    Points : 558
    Points
    558
    Par défaut
    J'ai beaucoup de mal a comprendre la ou tu veux en venir.
    Plus je te lis plus j'ai l'impression que tu as encore du mal a comprendre les objets que tu manipules.
    Je ne vais surement pas t'apprendre qu'un annuaire LDAP permet de stocker de facon structuré (un annuaire a une structure arborescente) des objets complexes.
    Plusieurs solutions pour trouver un object :
    - Donner le chemin complet dans l'arborescence de l'annuaire
    - effectuer une recherche basé sur des filtres

    Je suppose que c'est en utilisant des filtres que tu veux effectuer tes recherches. Je te suggère donc d'aller voir du coté de la méthode search de la class DirContext.
    Ensuite, il faut savoir qu'une recherche te permet de manipuler une collection d'objet LDAP. Mais dans tous les cas, un objet LDAP est représenté pas un objet de la classe Attributes (un objet LDAP correspond a un ensemble d'attribut)

    Et les objectClass dans tout ca ?? un objectclass n'est ni plus ni moins qu'un attibut particulier que possède n'importe quel objet LDAP. Pour simplifier, tu peux le voir un peu a la facon d'une interface dans le monde Java.
    Cela veux dire qu'un objectclass permet de définir quel sont les autres attributs que tu peux avoir dans ton objet LDAP.

    Si mon explication t'interesse et je pourrais éventuellement continuer demain. Mais en attendant... dodo :p

Discussions similaires

  1. [XPath][java] utiliser les nombres
    Par dingoth dans le forum XSL/XSLT/XPATH
    Réponses: 3
    Dernier message: 04/05/2009, 01h56
  2. Réponses: 1
    Dernier message: 20/02/2007, 18h47
  3. Réponses: 5
    Dernier message: 05/10/2006, 10h18
  4. Réponses: 2
    Dernier message: 10/07/2006, 18h19

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