KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > sf > jguard > ext > authentication > loginmodules > JdbcLoginModule


1 /*
2  jGuard is a security framework based on top of jaas (java authentication and authorization security).
3  it is written for web applications, to resolve simply, access control problems.
4  version $Name$
5  http://sourceforge.net/projects/jguard/
6
7  Copyright (C) 2004 Charles GAY
8
9  This library is free software; you can redistribute it and/or
10  modify it under the terms of the GNU Lesser General Public
11  License as published by the Free Software Foundation; either
12  version 2.1 of the License, or (at your option) any later version.
13
14  This library is distributed in the hope that it will be useful,
15  but WITHOUT ANY WARRANTY; without even the implied warranty of
16  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17  Lesser General Public License for more details.
18
19  You should have received a copy of the GNU Lesser General Public
20  License along with this library; if not, write to the Free Software
21  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22
23
24  jGuard project home page:
25  http://sourceforge.net/projects/jguard/
26
27  */

28 package net.sf.jguard.ext.authentication.loginmodules;
29
30 import java.sql.Connection JavaDoc;
31 import java.sql.PreparedStatement JavaDoc;
32 import java.sql.ResultSet JavaDoc;
33 import java.sql.SQLException JavaDoc;
34 import java.util.Map JavaDoc;
35 import java.util.Properties JavaDoc;
36 import java.util.logging.Level JavaDoc;
37 import java.util.logging.Logger JavaDoc;
38
39 import javax.security.auth.Subject JavaDoc;
40 import javax.security.auth.callback.CallbackHandler JavaDoc;
41 import javax.security.auth.login.FailedLoginException JavaDoc;
42 import javax.security.auth.login.LoginException JavaDoc;
43 import javax.security.auth.spi.LoginModule JavaDoc;
44
45 import net.sf.jguard.ext.authentication.manager.AuthenticationManagerFactory;
46 import net.sf.jguard.ext.authentication.manager.JdbcAuthenticationManager;
47 import net.sf.jguard.ext.database.ConnectionFactory;
48
49 /**
50  * LoginModule dedicated to Databases.
51  * @author <a HREF="mailto:diabolo512@users.sourceforge.net">Charles Gay</a>
52  * @see LoginModule
53  */

54 public class JdbcLoginModule extends UserLoginModule implements LoginModule JavaDoc {
55
56     static public final String JavaDoc CRED_VALUE = "cred_value";
57     static public final String JavaDoc CRED_NAME = "cred_name";
58     static public final String JavaDoc NAME = "name";
59
60     private static final String JavaDoc ID = "id";
61     private static final Logger JavaDoc logger = Logger.getLogger(JdbcLoginModule.class.getName());
62
63     private int userId = -1;
64
65     private ConnectionFactory connectionFactory;
66
67     private Properties JavaDoc props;
68
69     /**
70      * initialize database-related loginModule specifying 'digestAlgorithm', tables names,'applicationName', and connection
71      * parameters.
72      *
73      * @param subj
74      * @param cbkHandler
75      * @param sState
76      * @param opts
77      */

78     public void initialize(Subject JavaDoc subj, CallbackHandler JavaDoc cbkHandler, Map JavaDoc sState, Map JavaDoc opts) {
79         super.initialize(subj, cbkHandler, sState, opts);
80
81         JdbcAuthenticationManager authManager = (JdbcAuthenticationManager) AuthenticationManagerFactory
82                 .getAuthenticationManager();
83         props = authManager.getProperties();
84         connectionFactory = authManager.getConnectionFactory();
85
86     }
87
88     /**
89      * verify either user is registered or not.
90      *
91      * @see javax.security.auth.spi.LoginModule#login()
92      */

93     public boolean login() throws LoginException JavaDoc {
94         super.login();
95         userId = getUserID(login);
96         if (!skipPasswordCheck) {
97             boolean passwordValidated = false;
98             try{
99                 passwordValidated = validatePassword(new String JavaDoc(password));
100             }catch(LoginException JavaDoc e){
101                 loginOK = false;
102                 throw e;
103             }
104             logger.finest("password validation =" + passwordValidated + " for userId=" + userId);
105         }
106         return true;
107
108     }
109
110     private boolean validatePassword(String JavaDoc cryptedPassword) throws LoginException JavaDoc {
111         boolean authenticated;
112         Connection JavaDoc conn2 = null;
113         PreparedStatement JavaDoc pst2 = null;
114         ResultSet JavaDoc rs2 = null;
115         try {
116             conn2 = connectionFactory.getConnection();
117             pst2 = conn2.prepareStatement((String JavaDoc) props.get("USER_PASSWORD_EXIST"));
118             pst2.setInt(1, userId);
119             pst2.setString(2, new String JavaDoc(cryptedPassword));
120             rs2 = pst2.executeQuery();
121             authenticated = rs2.next();
122             if (authenticated == false) {
123                 if (logger.isLoggable(Level.FINEST)) {
124                     logger.finest(" password does not match ");
125                 }
126                 throw new FailedLoginException JavaDoc("login.password.does.not.match");
127             }
128         } catch (SQLException JavaDoc e2) {
129             if (logger.isLoggable(Level.SEVERE)) {
130                 logger.severe("login() - connection in " + this.getClass().getName() + " failed " + e2.getMessage());
131                 logger.severe("USER_PASSWORD_EXIST=" + props.get("USER_PASSWORD_EXIST"));
132             }
133             throw new LoginException JavaDoc(e2.getMessage());
134
135         } finally {
136             try {
137                 rs2.close();
138                 pst2.close();
139                 conn2.close();
140             } catch (SQLException JavaDoc e2) {
141                 if (logger.isLoggable(Level.SEVERE)) {
142                     logger.severe("login() - connection in MySQLLoginModule failed " + e2.getMessage());
143                 }
144             }
145         }
146         return authenticated;
147     }
148
149     private int getUserID(String JavaDoc login) throws LoginException JavaDoc {
150         boolean authenticated;
151         // check the login and grab the user id
152
ResultSet JavaDoc rs = null;
153         PreparedStatement JavaDoc pst = null;
154         Connection JavaDoc conn = null;
155         int userId = -1;
156         try {
157             conn = connectionFactory.getConnection();
158             pst = conn.prepareStatement((String JavaDoc) props.get("USER_LOGIN_EXIST"));
159             pst.setString(1, login);
160             rs = pst.executeQuery();
161             authenticated = rs.next();
162
163             if (authenticated == false) {
164                 if (logger.isLoggable(Level.FINEST)) {
165                     logger.finest(" user " + login + " does not exists ");
166                 }
167                 throw new FailedLoginException JavaDoc("login.user.does.not.exist");
168             }
169
170             userId = rs.getInt(JdbcLoginModule.ID);
171
172         } catch (SQLException JavaDoc e1) {
173             if (logger.isLoggable(Level.SEVERE)) {
174                 logger.severe("login() - connection " + e1.getMessage());
175             }
176             throw new LoginException JavaDoc(e1.getMessage());
177         } finally {
178             try {
179                 rs.close();
180                 pst.close();
181                 conn.close();
182             } catch (SQLException JavaDoc e2) {
183                 if (logger.isLoggable(Level.SEVERE)) {
184                     logger.severe("login() - connection failed " + e2.getMessage());
185                 }
186             }
187         }
188
189         return userId;
190     }
191
192     /**
193      * add Principals and Public/Private credentials to Subject.
194      *
195      * @see javax.security.auth.spi.LoginModule#commit()
196      */

197     public boolean commit() throws LoginException JavaDoc {
198         if(!loginOK){
199             return false;
200         }
201         try {
202             Subject JavaDoc subj = JdbcAuthenticationManager.getUser(userId);
203             // we copy the content into the real Subject
204
subject.getPrincipals().addAll(subj.getPrincipals());
205             subject.getPublicCredentials().addAll(subj.getPublicCredentials());
206             subject.getPrivateCredentials().addAll(subj.getPrivateCredentials());
207             if (logger.isLoggable(Level.FINEST)) {
208                 logger.finest(" user authenticated subject=" + subject);
209             }
210         } catch (SQLException JavaDoc e) {
211             logger.log(Level.SEVERE, "commit()", e);
212             throw new LoginException JavaDoc(e.getMessage());
213         }
214
215         return true;
216     }
217
218 }
219
Popular Tags