KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > infoglue > cms > security > JNDIBasicAuthenticationModule


1 /* ===============================================================================
2  *
3  * Part of the InfoGlue Content Management Platform (www.infoglue.org)
4  *
5  * ===============================================================================
6  *
7  * Copyright (C)
8  *
9  * This program is free software; you can redistribute it and/or modify it under
10  * the terms of the GNU General Public License version 2, as published by the
11  * Free Software Foundation. See the file LICENSE.html for more information.
12  *
13  * This program is distributed in the hope that it will be useful, but WITHOUT
14  * ANY WARRANTY, including the implied warranty of MERCHANTABILITY or FITNESS
15  * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License along with
18  * this program; if not, write to the Free Software Foundation, Inc. / 59 Temple
19  * Place, Suite 330 / Boston, MA 02111-1307 / USA.
20  *
21  * ===============================================================================
22  */

23
24 package org.infoglue.cms.security;
25
26 import java.io.Serializable JavaDoc;
27 import java.net.URLEncoder JavaDoc;
28 import java.security.Principal JavaDoc;
29 import java.util.HashMap JavaDoc;
30 import java.util.Hashtable JavaDoc;
31 import java.util.Map JavaDoc;
32 import java.util.Properties JavaDoc;
33
34 import javax.naming.Context JavaDoc;
35 import javax.naming.directory.DirContext JavaDoc;
36 import javax.naming.directory.InitialDirContext JavaDoc;
37 import javax.servlet.FilterChain JavaDoc;
38 import javax.servlet.ServletException JavaDoc;
39 import javax.servlet.http.HttpServletRequest JavaDoc;
40 import javax.servlet.http.HttpServletResponse JavaDoc;
41 import javax.servlet.http.HttpSession JavaDoc;
42
43 import org.apache.log4j.Logger;
44 import org.infoglue.cms.util.CmsPropertyHandler;
45
46 /**
47  * @author Mattias Bogeblad
48  *
49  * This authentication module authenticates an user against the ordinary infoglue database.
50  */

51
52 public class JNDIBasicAuthenticationModule extends AuthenticationModule
53 {
54     private final static Logger logger = Logger.getLogger(JNDIBasicAuthenticationModule.class.getName());
55     
56     private String JavaDoc loginUrl = null;
57     private String JavaDoc logoutUrl = null;
58     private String JavaDoc invalidLoginUrl = null;
59     private String JavaDoc successLoginUrl = null;
60     private String JavaDoc authenticatorClass = null;
61     private String JavaDoc authorizerClass = null;
62     private String JavaDoc serverName = null;
63     private String JavaDoc casServiceUrl = null;
64     private String JavaDoc casRenew = null;
65     private String JavaDoc casValidateUrl = null;
66     private String JavaDoc casLogoutUrl = null;
67     private String JavaDoc casAuthorizedProxy = null;
68     private Properties JavaDoc extraProperties = null;
69     
70     /**
71      * This method handles all of the logic for checking how to handle a login.
72      */

73     
74     public String JavaDoc authenticateUser(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response, FilterChain JavaDoc fc) throws Exception JavaDoc
75     {
76         String JavaDoc authenticatedUserName = null;
77         
78         HttpSession JavaDoc session = ((HttpServletRequest JavaDoc)request).getSession();
79         
80         //otherwise, we need to authenticate somehow
81
String JavaDoc userName = request.getParameter("j_username");
82         String JavaDoc password = request.getParameter("j_password");
83         String JavaDoc disableRedirect = (String JavaDoc)request.getAttribute("disableRedirect");
84         
85         // no userName? abort request processing and redirect
86
if (userName == null || userName.equals(""))
87         {
88             if (loginUrl == null)
89             {
90                 throw new ServletException JavaDoc(
91                         "When InfoGlueFilter protects pages that do not receive a 'userName' " +
92                         "parameter, it needs a org.infoglue.cms.security.loginUrl " +
93                         "filter parameter");
94             }
95             
96             String JavaDoc requestURI = request.getRequestURI();
97             
98             String JavaDoc requestQueryString = request.getQueryString();
99             if(requestQueryString != null)
100             {
101                 requestQueryString = "?" + requestQueryString;
102             }
103             else
104             {
105                 requestQueryString = "";
106             }
107             
108             logger.info("requestQueryString:" + requestQueryString);
109             
110             String JavaDoc redirectUrl = "";
111             
112             if(requestURI.indexOf("?") > 0)
113             {
114                 redirectUrl = loginUrl + "&referringUrl=" + URLEncoder.encode(requestURI + requestQueryString, "UTF-8") + "&returnAddress=" + URLEncoder.encode(requestURI + requestQueryString, "UTF-8");
115             }
116             else
117             {
118                 redirectUrl = loginUrl + "?referringUrl=" + URLEncoder.encode(requestURI + requestQueryString, "UTF-8") + "&returnAddress=" + URLEncoder.encode(requestURI + requestQueryString, "UTF-8");
119             }
120             
121             logger.info("redirectUrl:" + redirectUrl);
122             if(disableRedirect == null || !disableRedirect.equals("true"))
123                 response.sendRedirect(redirectUrl);
124             
125             return null;
126         }
127         
128         boolean isAuthenticated = authenticate(userName, password, new HashMap JavaDoc());
129         logger.info("authenticated:" + isAuthenticated);
130         authenticatedUserName = userName;
131         
132         if(!isAuthenticated)
133         {
134             String JavaDoc referringUrl = request.getRequestURI();
135             if(request.getParameter("referringUrl") != null)
136                 referringUrl = request.getParameter("referringUrl");
137             
138             String JavaDoc requestQueryString = request.getQueryString();
139             if(requestQueryString != null)
140                 requestQueryString = "?" + requestQueryString;
141             else
142                 requestQueryString = "";
143             
144             logger.info("requestQueryString:" + requestQueryString);
145             
146             String JavaDoc redirectUrl = "";
147             
148             if(referringUrl.indexOf("?") > 0)
149                 redirectUrl = invalidLoginUrl + "?userName=" + URLEncoder.encode(userName, "UTF-8") + "&errorMessage=" + URLEncoder.encode("Invalid login - please try again..", "UTF-8") + "&referringUrl=" + URLEncoder.encode(referringUrl + requestQueryString, "UTF-8") + "&returnAddress=" + URLEncoder.encode(referringUrl + requestQueryString, "UTF-8");
150             else
151                 redirectUrl = invalidLoginUrl + "?userName=" + URLEncoder.encode(userName, "UTF-8") + "?errorMessage=" + URLEncoder.encode("Invalid login - please try again..", "UTF-8") + "&referringUrl=" + URLEncoder.encode(referringUrl + requestQueryString, "UTF-8") + "&returnAddress=" + URLEncoder.encode(referringUrl + requestQueryString, "UTF-8");
152             
153             //String redirectUrl = invalidLoginUrl + "?userName=" + URLEncoder.encode(userName, "UTF-8") + "&errorMessage=" + URLEncoder.encode("Invalid login - please try again..", "UTF-8") + "&referringUrl=" + URLEncoder.encode(referringUrl + requestQueryString, "UTF-8");
154
logger.info("redirectUrl:" + redirectUrl);
155             if(disableRedirect == null || !disableRedirect.equals("true"))
156                 response.sendRedirect(redirectUrl);
157             
158             return null;
159         }
160         
161         //fc.doFilter(request, response);
162
return authenticatedUserName;
163     }
164     
165     
166     /**
167      * This method handles all of the logic for checking how to handle a login.
168      */

169     
170     public String JavaDoc authenticateUser(Map JavaDoc request) throws Exception JavaDoc
171     {
172         String JavaDoc authenticatedUserName = null;
173         
174         //otherwise, we need to authenticate somehow
175
String JavaDoc userName = (String JavaDoc)request.get("j_username");
176         String JavaDoc password = (String JavaDoc)request.get("j_password");
177         
178         logger.info("authenticateUser:userName:" + userName);
179         
180         // no userName? abort request processing and redirect
181
if (userName == null || userName.equals(""))
182         {
183             return null;
184         }
185         
186         boolean isAuthenticated = authenticate(userName, password, new HashMap JavaDoc());
187         logger.info("authenticated:" + isAuthenticated);
188         
189         if(!isAuthenticated)
190         {
191             return null;
192         }
193         
194         authenticatedUserName = userName;
195         
196         return authenticatedUserName;
197     }
198     
199     
200     /**
201      * This method handles all of the logic for checking how to handle a login.
202      */

203     
204     public String JavaDoc getLoginDialogUrl(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) throws Exception JavaDoc
205     {
206         if(CmsPropertyHandler.getApplicationName().equals("deliver"))
207         {
208             logger.info("It was a deliver request... let's keep it simple...");
209             String JavaDoc returnAddress = null;
210     
211             String JavaDoc referer = request.getHeader("Referer");
212             
213             if(referer == null || referer.indexOf("ViewStructureToolToolBar.action") != -1)
214                 referer = "/";
215     
216             logger.info("successLoginUrl:" + successLoginUrl);
217             if(successLoginUrl != null)
218             {
219                 returnAddress = successLoginUrl;
220             }
221             else
222             {
223                 returnAddress = request.getRequestURL().toString() + "?" + request.getQueryString() + "&referer=" + URLEncoder.encode(referer, "UTF-8") + "&date=" + System.currentTimeMillis();
224             }
225             
226             logger.info("returnAddress:" + returnAddress);
227             return request.getContextPath() + "/ExtranetLogin!loginForm.action?returnAddress=" + URLEncoder.encode(returnAddress, "UTF-8");
228         }
229         
230         String JavaDoc url = null;
231
232         //otherwise, we need to authenticate somehow
233
String JavaDoc userName = request.getParameter("j_username");
234         String JavaDoc password = request.getParameter("j_password");
235         
236         // no userName? abort request processing and redirect
237
if (userName == null || userName.equals(""))
238         {
239             if (loginUrl == null)
240             {
241                 throw new ServletException JavaDoc(
242                         "When InfoGlueFilter protects pages that do not receive a 'userName' " +
243                         "parameter, it needs a org.infoglue.cms.security.loginUrl " +
244                         "filter parameter");
245             }
246             
247             String JavaDoc requestURI = request.getRequestURI();
248             
249             String JavaDoc requestQueryString = request.getQueryString();
250             if(requestQueryString != null)
251             {
252                 requestQueryString = "?" + requestQueryString;
253             }
254             else
255             {
256                 requestQueryString = "";
257             }
258             
259             logger.info("requestQueryString:" + requestQueryString);
260             
261             String JavaDoc redirectUrl = "";
262             
263             if(requestURI.indexOf("?") > 0)
264             {
265                 redirectUrl = loginUrl + "&referringUrl=" + URLEncoder.encode(requestURI + requestQueryString, "UTF-8") + "&returnAddress=" + URLEncoder.encode(requestURI + requestQueryString, "UTF-8");
266             }
267             else
268             {
269                 redirectUrl = loginUrl + "?referringUrl=" + URLEncoder.encode(requestURI + requestQueryString, "UTF-8") + "&returnAddress=" + URLEncoder.encode(requestURI + requestQueryString, "UTF-8");
270             }
271             
272             logger.info("redirectUrl:" + redirectUrl);
273             return redirectUrl;
274         }
275         
276         boolean isAuthenticated = authenticate(userName, password, new HashMap JavaDoc());
277         logger.info("authenticated:" + isAuthenticated);
278         String JavaDoc authenticatedUserName = userName;
279         
280         if(!isAuthenticated)
281         {
282             String JavaDoc referringUrl = request.getRequestURI();
283             if(request.getParameter("referringUrl") != null)
284                 referringUrl = request.getParameter("referringUrl");
285             
286             String JavaDoc requestQueryString = request.getQueryString();
287             if(requestQueryString != null)
288                 requestQueryString = "?" + requestQueryString;
289             else
290                 requestQueryString = "";
291             
292             logger.info("requestQueryString:" + requestQueryString);
293             
294             String JavaDoc redirectUrl = "";
295             
296             if(referringUrl.indexOf("?") > 0)
297                 redirectUrl = invalidLoginUrl + "?userName=" + URLEncoder.encode(userName, "UTF-8") + "&errorMessage=" + URLEncoder.encode("Invalid login - please try again..", "UTF-8") + "&referringUrl=" + URLEncoder.encode(referringUrl + requestQueryString, "UTF-8") + "&returnAddress=" + URLEncoder.encode(referringUrl + requestQueryString, "UTF-8");
298             else
299                 redirectUrl = invalidLoginUrl + "?userName=" + URLEncoder.encode(userName, "UTF-8") + "?errorMessage=" + URLEncoder.encode("Invalid login - please try again..", "UTF-8") + "&referringUrl=" + URLEncoder.encode(referringUrl + requestQueryString, "UTF-8") + "&returnAddress=" + URLEncoder.encode(referringUrl + requestQueryString, "UTF-8");
300             
301             //String redirectUrl = invalidLoginUrl + "?userName=" + URLEncoder.encode(userName, "UTF-8") + "&errorMessage=" + URLEncoder.encode("Invalid login - please try again..", "UTF-8") + "&referringUrl=" + URLEncoder.encode(referringUrl + requestQueryString, "UTF-8");
302
logger.info("redirectUrl:" + redirectUrl);
303             return redirectUrl;
304         }
305
306         return url;
307     }
308
309     /**
310      * This method authenticates against the infoglue extranet user database.
311      */

312     
313     private boolean authenticate(String JavaDoc userName, String JavaDoc password, Map JavaDoc parameters) throws Exception JavaDoc
314     {
315         boolean isAuthenticated = false;
316         
317         String JavaDoc administratorUserName = CmsPropertyHandler.getAdministratorUserName();
318         String JavaDoc administratorPassword = CmsPropertyHandler.getAdministratorPassword();
319         //logger.info("administratorUserName:" + administratorUserName);
320
//logger.info("administratorPassword:" + administratorPassword);
321
//logger.info("userName:" + userName);
322
//logger.info("password:" + password);
323
boolean isAdministrator = (userName.equalsIgnoreCase(administratorUserName) && password.equalsIgnoreCase(administratorPassword)) ? true : false;
324         
325         if(isAdministrator || bindUserUsingJNDI(userName, password))
326         {
327             isAuthenticated = true;
328         }
329         
330         return isAuthenticated;
331     }
332     
333     public Principal JavaDoc loginUser(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response, Map JavaDoc status) throws Exception JavaDoc
334     {
335         return null;
336     }
337
338     public boolean logoutUser(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) throws Exception JavaDoc
339     {
340         return false;
341     }
342     
343     private boolean bindUserUsingJNDI(String JavaDoc userName, String JavaDoc password)
344     {
345         if(password == null || password.equals(""))
346         {
347             String JavaDoc allowAnonymousBind = this.extraProperties.getProperty("allowAnonymousBind");
348             if(allowAnonymousBind == null || !allowAnonymousBind.equalsIgnoreCase("true"))
349             {
350                 logger.warn("Anonymous bind attemped by not giving any password. Not allowed - now using password '--No password given but anonymous binds not allowed--'");
351                 password = "--No password given but anonymous binds not allowed--";
352             }
353         }
354         
355         boolean result = false;
356         DirContext JavaDoc ctx = null;
357         String JavaDoc connectionURL = this.extraProperties.getProperty("connectionURL");
358         String JavaDoc ldapUserName = this.extraProperties.getProperty("userNamePattern");
359         
360         String JavaDoc anonymousUserName = CmsPropertyHandler.getAnonymousUser();
361         if(userName.equals(anonymousUserName))
362         {
363             ldapUserName = this.extraProperties.getProperty("anonymousUserNamePattern");
364         }
365
366         ldapUserName = ldapUserName.replaceFirst("infoglue.user", userName);
367
368         Hashtable JavaDoc env = new Hashtable JavaDoc();
369         
370         env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
371         env.put(Context.PROVIDER_URL, connectionURL);
372         env.put(Context.SECURITY_AUTHENTICATION, "simple");
373         env.put(Context.SECURITY_PRINCIPAL, ldapUserName);
374         env.put(Context.SECURITY_CREDENTIALS, password);
375         
376         try
377         {
378             ctx = new InitialDirContext JavaDoc(env);
379             logger.info("User: " + ldapUserName + " successfully bound.");
380             ctx.close();
381             result = true;
382         }
383         catch (Exception JavaDoc e)
384         {
385             logger.info("Could not bind user: " + ldapUserName + ", " + e.getMessage());
386         }
387                 
388         return result;
389     }
390     
391     public String JavaDoc getAuthenticatorClass()
392     {
393         return authenticatorClass;
394     }
395     
396     public void setAuthenticatorClass(String JavaDoc authenticatorClass)
397     {
398         this.authenticatorClass = authenticatorClass;
399     }
400     
401     public String JavaDoc getAuthorizerClass()
402     {
403         return authorizerClass;
404     }
405     
406     public void setAuthorizerClass(String JavaDoc authorizerClass)
407     {
408         this.authorizerClass = authorizerClass;
409     }
410     
411     public String JavaDoc getInvalidLoginUrl()
412     {
413         return invalidLoginUrl;
414     }
415     
416     public void setInvalidLoginUrl(String JavaDoc invalidLoginUrl)
417     {
418         this.invalidLoginUrl = invalidLoginUrl;
419     }
420     
421     public String JavaDoc getLoginUrl()
422     {
423         return loginUrl;
424     }
425     
426     public void setLoginUrl(String JavaDoc loginUrl)
427     {
428         this.loginUrl = loginUrl;
429     }
430     
431     public String JavaDoc getLogoutUrl()
432     {
433         return logoutUrl;
434     }
435
436     public void setLogoutUrl(String JavaDoc logoutUrl)
437     {
438         this.logoutUrl = logoutUrl;
439     }
440
441     public String JavaDoc getSuccessLoginUrl()
442     {
443         return successLoginUrl;
444     }
445     
446     public void setSuccessLoginUrl(String JavaDoc successLoginUrl)
447     {
448         this.successLoginUrl = successLoginUrl;
449     }
450     
451     public String JavaDoc getServerName()
452     {
453         return this.serverName;
454     }
455     
456     public void setServerName(String JavaDoc serverName)
457     {
458         this.serverName = serverName;
459     }
460     
461     public Properties JavaDoc getExtraProperties()
462     {
463         return extraProperties;
464     }
465     
466     public void setExtraProperties(Properties JavaDoc extraProperties)
467     {
468         this.extraProperties = extraProperties;
469     }
470     
471     public String JavaDoc getCasRenew()
472     {
473         return casRenew;
474     }
475     
476     public void setCasRenew(String JavaDoc casRenew)
477     {
478         this.casRenew = casRenew;
479     }
480     
481     public String JavaDoc getCasServiceUrl()
482     {
483         return casServiceUrl;
484     }
485     
486     public void setCasServiceUrl(String JavaDoc casServiceUrl)
487     {
488         this.casServiceUrl = casServiceUrl;
489     }
490     
491     public String JavaDoc getCasValidateUrl()
492     {
493         return casValidateUrl;
494     }
495     
496     public void setCasValidateUrl(String JavaDoc casValidateUrl)
497     {
498         this.casValidateUrl = casValidateUrl;
499     }
500     
501     public String JavaDoc getCasAuthorizedProxy()
502     {
503         return casAuthorizedProxy;
504     }
505     
506     public void setCasAuthorizedProxy(String JavaDoc casAuthorizedProxy)
507     {
508         this.casAuthorizedProxy = casAuthorizedProxy;
509     }
510     
511     public Object JavaDoc getTransactionObject()
512     {
513         return null;
514     }
515     
516     public void setTransactionObject(Object JavaDoc transactionObject)
517     {
518     }
519
520
521     public String JavaDoc getCasLogoutUrl()
522     {
523         return casLogoutUrl;
524     }
525
526
527     public void setCasLogoutUrl(String JavaDoc casLogoutUrl)
528     {
529         this.casLogoutUrl = casLogoutUrl;
530     }
531     
532 }
Popular Tags