KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tdsecurities > itracker > security > LdapAuthenticate


1 package com.tdsecurities.itracker.security;
2
3 import java.util.Hashtable JavaDoc;
4
5 import javax.naming.AuthenticationException JavaDoc;
6 import javax.naming.Context JavaDoc;
7 import javax.naming.NamingEnumeration JavaDoc;
8 import javax.naming.NamingException JavaDoc;
9 import javax.naming.directory.DirContext JavaDoc;
10 import javax.naming.directory.InitialDirContext JavaDoc;
11 import javax.naming.directory.SearchControls JavaDoc;
12 import javax.naming.directory.SearchResult JavaDoc;
13
14 /**
15  */

16 public class LdapAuthenticate
17 {
18     public static final int LOGIN_SUCCESS = 0;
19     public static final int USER_NOT_EXIST = 1;
20     public static final int WRONG_PASSWORD = 2;
21     public static final int UNKNOWN_ERROR = 3;
22     
23     // LDAP servers
24
public static final String JavaDoc [] PROVIDER_URL =
25     {
26         "ldap://ldap1.com:389",
27         "ldap://ldap2.com:389",
28         "ldap://ldap3.com:389",
29         "ldap://ldap4.com:389",
30     };
31     // Search LDAP server for how many times
32
private static final int CYCLE = 2;
33     // Should we print out debug message
34
private static final boolean DEBUG = false;
35     
36     // basic LDAP search information
37
public static String JavaDoc SECURITY_PRINCIPAL = "";
38     public static String JavaDoc SECURITY_CREDENTIALS = "";
39     public static String JavaDoc SEARCH_DOMAIN = "";
40     
41     // The active server id
42
private int active = 0;
43     private DirContext JavaDoc dirctx = null;
44     private DirContext JavaDoc ctx = null;
45     
46     /**
47      * Constructor, used to create assign the value for
48      * PRINCIPAL, CREDENTIAL and SEARCH_DOMAIN information
49      */

50     public LdapAuthenticate()
51     {
52         // We can read these credential information from a properties file
53
SECURITY_PRINCIPAL = "cn=svc,ou=serviceaccounts,ou=bc,dc=corp,dc=acme,dc=com";
54         SECURITY_CREDENTIALS = "cred";
55         SEARCH_DOMAIN = "dc=corp,dc=acme,dc=com";
56     }
57
58     /**
59      * Go through all the LDAP server to login
60      */

61     private void initDirContext()
62         throws NamingException JavaDoc
63     {
64         // number of cycle for round robin
65
for (int j = 0; j < CYCLE; j++)
66         {
67             // round robin
68
for (int i = 0; i < PROVIDER_URL.length; i++)
69             {
70                 active = i;
71                 try
72                 {
73                     log ("Trying LDAP Server: " + PROVIDER_URL[active] + " ...");
74                     dirctx = getDirContext(
75                         PROVIDER_URL[active], SECURITY_PRINCIPAL, SECURITY_CREDENTIALS);
76                     log ("Successfully connected to LDAP Server: " + PROVIDER_URL[active]);
77                     return;
78                 }
79                 catch( NamingException JavaDoc e )
80                 {
81                     log ("Failed to connect to LDAP Server #" + i + ": " + PROVIDER_URL[active]);
82                     log ("Reason:" + e);
83                     closeDirContext();
84                 }
85             }
86         }
87         log ("None of the LDAP server can be connected.");
88         throw new NamingException JavaDoc(
89             "None of the LDAP server can be connected");
90     }
91
92     /**
93      * Close the all the directory context
94      * Do not throw exception from here
95      */

96     private void closeDirContext()
97     {
98         try
99         {
100             if (dirctx != null)
101             {
102                 dirctx.close();
103             }
104             if (ctx != null)
105             {
106                 ctx.close();
107             }
108         }
109         catch(NamingException JavaDoc e)
110         {
111             log("Could not close the connection to LDAP server - " + e );
112         }
113     }
114     
115     /**
116      * This method gets an active directory context
117      *
118      * @param ldap_url URL to connect to LDAP server
119      * @param login LDAP login ID
120      * @param password LDAP Password
121      */

122     private DirContext JavaDoc getDirContext(
123         String JavaDoc ldap_url, String JavaDoc login, String JavaDoc passwd)
124         throws NamingException JavaDoc
125     {
126         // connect to active directory
127
Hashtable JavaDoc env = new Hashtable JavaDoc();
128         env.put( Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
129         env.put( Context.SECURITY_AUTHENTICATION, "simple");
130         env.put( "com.sun.indi.ldap.trace.ber", System.err );
131
132         env.put( Context.PROVIDER_URL, ldap_url);
133         env.put( Context.SECURITY_PRINCIPAL, login);
134         env.put( Context.SECURITY_CREDENTIALS, passwd);
135
136         return new InitialDirContext JavaDoc( env );
137     }
138
139     /**
140      * This method provides a functionality to authenticate a Login/Password combination, using
141      * LDAP Server.
142      *
143      * @param login Login ID to be authenticated
144      * @param password Login ID to be authenticated
145      */

146     public int doAuthentication(String JavaDoc login, String JavaDoc password)
147         throws NamingException JavaDoc
148     {
149         int result = UNKNOWN_ERROR;
150         log ("Start searching for user " + login);
151
152         try
153         {
154             initDirContext();
155             SearchControls JavaDoc searchControls = new SearchControls JavaDoc();
156             searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
157             // Search for objects using the filter
158
NamingEnumeration JavaDoc answer = dirctx.search(
159                 SEARCH_DOMAIN, "(&(sAMAccountName=" + login + "))", searchControls);
160
161             if (answer.hasMore())
162             {
163                 SearchResult JavaDoc searchResult = (SearchResult JavaDoc)answer.next();
164                 String JavaDoc userName = searchResult.getName();
165                 log("User found : " + userName);
166                 ctx = getDirContext(
167                         PROVIDER_URL[active], userName + "," + SEARCH_DOMAIN, password);
168                 result = LOGIN_SUCCESS;
169             }
170             else
171             {
172                 log("User NOT found.");
173                 result = USER_NOT_EXIST;
174             }
175         }
176         catch( AuthenticationException JavaDoc e )
177         {
178             log("Invalid password. Logon failed." );
179             result = WRONG_PASSWORD;
180         }
181         finally
182         {
183             closeDirContext();
184         }
185         return result;
186     }
187
188     public LdapDistinguishedName getAttributesFromLoginId(String JavaDoc login)
189         throws NamingException JavaDoc
190     {
191         LdapDistinguishedName ldapName = null;
192
193         if (login == null)
194         {
195             return null;
196         }
197
198         try
199         {
200             initDirContext();
201             SearchControls JavaDoc ctls = new SearchControls JavaDoc();
202             ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
203
204             // Search for objects using the filter
205
NamingEnumeration JavaDoc answer =
206                 dirctx.search(SEARCH_DOMAIN, "(&(sAMAccountName=" + login + "))", ctls);
207
208             if(answer.hasMore())
209             {
210                 SearchResult JavaDoc searchResult = (SearchResult JavaDoc) answer.next();
211                 ldapName = new LdapDistinguishedName(searchResult.getAttributes());
212                 log(ldapName.toString());
213             }
214         }
215         finally
216         {
217             closeDirContext();
218         }
219         return ldapName;
220     }
221
222     /**
223      * Keep the log of the LDAP authentication
224      */

225     protected void log (String JavaDoc s)
226     {
227         if (DEBUG)
228         {
229             System.out.println("<LDAPAuthenticate> - " + s);
230         }
231     }
232 }
233
Popular Tags