KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > enhydra > shark > authentication > LDAPClient


1 package org.enhydra.shark.authentication;
2
3 import org.enhydra.shark.api.internal.working.CallbackUtilities;
4
5 import java.util.*;
6
7 import javax.naming.*;
8 import javax.naming.directory.*;
9
10 /**
11  * Connects to the LDAP server and gets wanted entries.
12  *
13  * @author Sasa Bojanic, Tanja Jovanovic
14  * @version 1.0
15  */

16 public class LDAPClient {
17    private final String JavaDoc boundary=",";
18
19    private LDAPOptions ldapOptions;
20
21    private CallbackUtilities cus;
22    
23    private java.util.Properties JavaDoc env = new java.util.Properties JavaDoc();
24    
25    private SearchControls constraints=new SearchControls();
26
27    /**
28     * Public constructor (CallbackUtilities).
29     */

30    public LDAPClient (CallbackUtilities cus) {
31       this.cus=cus;
32       ldapOptions=new LDAPOptions(cus);
33       /* Create an environment for the initial directory context.
34        The properties specify the LDAP provider, the LDAP server,
35        and if needed username and password, or if not, no security
36        (anonymous bind). */

37       env = new java.util.Properties JavaDoc();
38       env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
39       env.put(javax.naming.Context.REFERRAL, "throw");
40       env.put(javax.naming.Context.PROVIDER_URL, "ldap://" + ldapOptions.getHost() + ":" + ldapOptions.getPort());
41       env.put(javax.naming.Context.SECURITY_PRINCIPAL, ldapOptions.getUser());
42       env.put(javax.naming.Context.SECURITY_CREDENTIALS, ldapOptions.getPassword());
43
44       // Set up and perform the search.
45
constraints.setSearchScope(ldapOptions.getSearchScope());
46       constraints.setCountLimit(0);
47    }
48
49    /**
50     * Used to retreive LDAPOptions object, which might be set other
51     * then default before calling getEntries.
52     *
53     * @return LDAPOptions object.
54     */

55    public LDAPOptions getLDAPOptions () {
56       return ldapOptions;
57    }
58
59    /**
60     * Connects to the LDAP server specified by LDAPOptions object, and
61     * checks given password.
62     *
63     * @param username User distinctive name.
64     * @param pwd Password to check for the given user.
65     * @return true if password is OK.
66     */

67    public boolean checkPassword (String JavaDoc username,String JavaDoc pwd) {
68 //System.err.println("Checking pwd "+pwd+" for user "+username);
69
try {
70          String JavaDoc base = ldapOptions.getSearchBase();
71          String JavaDoc filter="";
72          String JavaDoc[] objClasses;
73          Iterator results;
74          SearchResult sr;
75          String JavaDoc dn = null;
76          int count = 0;
77
78          if (ldapOptions.getStructureType() == 1) {
79             objClasses=tokenize(ldapOptions.getGroupObjectClasses(),boundary);
80             if (objClasses!=null && objClasses.length>0) {
81                if (objClasses.length>1) {
82                   filter+="(|";
83                }
84                for (int i=0; i<objClasses.length; i++) {
85                   filter+="(objectClass="+objClasses[i]+")";
86                }
87                if (objClasses.length>1) {
88                   filter+=")";
89                }
90             }
91             filter="(&("+ldapOptions.getGroupUniqueAttributeName()+"=" + ldapOptions.getGroupUsersName()+ ")"+filter+")";
92             results=getEntries(filter).iterator();
93             if (results.hasNext()) {
94                sr = (SearchResult) results.next();
95 // attributes = sr.getAttributes();
96
try {
97                   dn = sr.getName();
98                }
99                catch (Exception JavaDoc e){}
100                if (!dn.equals("")){
101                   if (!base.equals("")){
102                      dn = dn + "," + base;
103                   }
104                }
105                else {
106                   dn = base;
107                }
108                ldapOptions.setSearchBase(dn);
109
110                filter="";
111                objClasses=tokenize(ldapOptions.getUserObjectClasses(),boundary);
112                if (objClasses!=null && objClasses.length>0) {
113                   if (objClasses.length>1) {
114                      filter+="(|";
115                   }
116                   for (int i=0; i<objClasses.length; i++) {
117                      filter+="(objectClass="+objClasses[i]+")";
118                   }
119                   if (objClasses.length>1) {
120                      filter+=")";
121                   }
122                }
123                filter="(&("+ldapOptions.getUserUniqueAttributeName()+"="+username+")"+
124                            "("+ldapOptions.getUserPasswordAttributeName()+"="+pwd+")"+
125                            filter+")";
126                 count = getEntries(filter).size();
127
128                ldapOptions.setSearchBase(base);
129              }
130          } // if (ldapOptions.getStructureType() == 1)
131
else {
132             objClasses=tokenize(ldapOptions.getUserObjectClasses(),boundary);
133             if (objClasses!=null && objClasses.length>0) {
134                if (objClasses.length>1) {
135                  filter+="(|";
136                }
137                for (int i=0; i<objClasses.length; i++) {
138                   filter+="(objectClass="+objClasses[i]+")";
139                }
140                if (objClasses.length>1) {
141                   filter+=")";
142                }
143             }
144             filter="(&("+ldapOptions.getUserUniqueAttributeName()+"="+username+")"+
145                "("+ldapOptions.getUserPasswordAttributeName()+"="+pwd+")"+
146                filter+")";
147             count = getEntries(filter).size();
148          }
149
150          return count > 0;
151
152       } catch (NamingException e) {
153          /* Handle any name/directory exceptions. */
154 cus.warn("LDAPClient -> Search failed: "+e.getMessage());
155       }
156       catch (Exception JavaDoc e) {
157          /* Handle any other types of exceptions. */
158 cus.warn("LDAPClient -> Non-naming error: " + e.getMessage());
159       }
160       catch (Throwable JavaDoc e) {
161          /* Handle any other types of exceptions. */
162 cus.warn("LDAPClient -> Non-naming error: " + e.getMessage());
163       }
164       return false;
165    }
166    
167    /**
168     * Connects to the LDAP server and retrieves wanted data.
169     * All neccessary information to establish connection to the server, and
170     * to retrieve data are hold within LDAPOptions.
171     */

172    private java.util.List JavaDoc getEntries (String JavaDoc filter) throws Throwable JavaDoc {
173       java.util.List JavaDoc entries=new java.util.ArrayList JavaDoc();
174       DirContext ctx=new InitialDirContext(env);
175       try {
176 //System.out.println("GTQ for "+filter);
177
NamingEnumeration results = ctx.search(
178             ldapOptions.getSearchBase(),
179             filter,
180             constraints);
181          /* For each entry found. */
182 //int i=0;
183
while (results.hasMore()) {
184 //System.out.println("FE"+(i++));
185
SearchResult sr = (SearchResult) results.next();
186             entries.add(sr);
187          }
188 //System.out.println("Returning "+i+" entr");
189
return entries;
190       }
191       catch (Exception JavaDoc e){
192         e.printStackTrace();
193         }
194        finally {
195          ctx.close();
196       }
197       return entries;
198    }
199
200    /**
201     * Take the given string and chop it up into a series
202     * of strings on given boundries. This is useful
203     * for trying to get an array of strings out of the
204     * resource file.
205     *
206     * @param input input string.
207     * @param boundary boundary string.
208     * @return array of result strings.
209     */

210    static String JavaDoc[] tokenize(String JavaDoc input,String JavaDoc boundary) {
211       if (input==null) input="";
212       Vector v = new Vector();
213       StringTokenizer t = new StringTokenizer(input,boundary);
214       String JavaDoc cmd[];
215
216       while (t.hasMoreTokens())
217          v.addElement(t.nextToken());
218       cmd = new String JavaDoc[v.size()];
219       for (int i = 0; i < cmd.length; i++)
220          cmd[i] = (String JavaDoc)v.elementAt(i);
221
222       return cmd;
223    }
224
225 }
226
Popular Tags