Please Help with my Servlet authentication method
Hi,
I am trying to authenticate the user to access certain pages but I can't find the error in the authentication method am using.It keeps on returning "false" for valid entries.I created a table in MySql DB with users and passwords. I am wondering whether its because am storing the password in an encrypted form.When I enter a certain username with its corresponding password the methods doesn't return true. I have hard coded one of the usernames (alex)in the code below as strings that I pass to my method. I am using JNDI in tomcat 5.5 for database access. I am getting the database connection through my DAO.java class.
I will be grateful if I could also be guided on the best way to make my database access code good to maximise its reuse as I will have many action classes accessing my db. I have read its not good to have it in the init method of the servlet. I am new to this so bear with my code structure.
DAO.java
package zambezi_stuff;
import java.sql.*;
import javax.naming.NamingException;
import javax.sql.*;
import javax.naming.InitialContext;
import java.util.*;
publicclass DAO{
publicstatic Connection getDbConnection(String jndiDS)
throws SQLException{
DataSource ds =null;
Connection conn =null;
InitialContext initCxt =null;
try{
initCxt =new InitialContext();
ds = (DataSource)initCxt.lookup(jndiDS);
conn = ds.getConnection();
}catch (SQLException ex){
ex.printStackTrace();
}catch (NamingException ex){
ex.printStackTrace();
}
return conn;
}
}
TestAuthenticationServlet.java
package zambezi_stuff;
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
publicclass NewServletextends HttpServlet{
protectedvoid processRequest(HttpServletRequest _reqst,
HttpServletResponse _resp)
throws ServletException, IOException{
_resp.setContentType("text/html;charset=UTF-8");
PrintWriter out = _resp.getWriter();
String userName ="alex";//_reqst.getParameter("userName");
String password ="alex";//_reqst.getParameter("password");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet NewServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Test Authentication</h1>");
out.println("<table>");
out.println("<tr><td>");
out.println("<tr><td>");
out.println(authenticate(userName,password));
out.println("</table>");
out.println("</body>");
out.println("</html>");
}
publicboolean authenticate(String userName, String password){
boolean validUser =false;
String jndiDS ="java:comp/env/jdbc/musicClub";
String _sqlQry ="select * from tblLogin where userName = '" + userName +"' and password = '" + password +"'";
String dbPsswd;
String dbUser;
Connection conn =null;
Statement stat =null;
ResultSet rst =null;
try{
DAO dao =new DAO();
conn = dao.getDbConnection(jndiDS);
stat = conn.createStatement();
rst = stat.executeQuery(_sqlQry);
while(rst.next()){
dbUser = rst.getString("userName");
dbPsswd = rst.getString("password");
if(dbUser.equals(userName) && dbPsswd.equals(password)){
validUser =true;
}else{
validUser =false;
}
}
}catch(SQLException _sqlExp){
_sqlExp.printStackTrace();
}/*finally{
if(rst!=null){
try{
rst.close();
}catch(SQLException sqlexp){}
}if(stat!=null){
try{
stat.close();
}catch(SQLException sqlexp){}
}if(conn!=null){
try{
conn.close();
}catch(SQLException sqlexp){}
}
}*/
return validUser;
}
protectedvoid doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
processRequest(request, response);
}
protectedvoid doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
processRequest(request, response);
}
}
Thank you in advance for any help.
[7583 byte] By [
aiExa] at [2007-11-27 6:02:24]

# 1
This is a regular mistake we people do when parsing through the recordset.....
in your TestAuthenticationServlet.java....in authenticate method...change u have the while loop as following ...
-
while(rst.next()){
dbUser = rst.getString("userName");
dbPsswd = rst.getString("password");
if(dbUser.equals(userName) && dbPsswd.equals(password)){
validUser = true;
}else{
validUser = false;
}
}
-
now change it to folowing :
--
while(rst.next()){
dbUser = rst.getString("userName");
dbPsswd = rst.getString("password");
if(dbUser.equals(userName) && dbPsswd.equals(password)){
validUser = true;
break;
}else{
validUser = false;
}
}
-
a break statement was needed :)
Hope this helps...
Thanks
# 2
Thanx for the quick reply. I have changed as you suggested but still doest work....
package zambezi_stuff;
[b]TestAuthenticationServlet[/b]
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class TestAuthenticationServlet extends HttpServlet{
protected void processRequest(HttpServletRequest _reqst,
HttpServletResponse _resp)
throws ServletException, IOException {
_resp.setContentType("text/html;charset=UTF-8");
PrintWriter out = _resp.getWriter();
String userName = "alex";//_reqst.getParameter("userName");
String password = "alex";//_reqst.getParameter("password");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet NewServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Test Authentication Servlet</h1>");
out.println("<table>");
out.println("<tr><td>");
out.println("<tr><td>");
out.println(authenticate(userName,password));
out.println("</table>");
out.println("</body>");
out.println("</html>");
}
public boolean authenticate(String userName, String password){
boolean validUser = false;
String jndiDS = "java:comp/env/jdbc/musicClub";
String _sqlQry = "select * from tblLogin where userName = '" + userName + "' and password = '" + password + "'";
String dbPsswd;
String dbUser;
Connection conn = null;
Statement stat = null;
ResultSet rst = null;
try{
DAO dao = new DAO();
conn = dao.getDbConnection(jndiDS);
stat = conn.createStatement();
rst = stat.executeQuery(_sqlQry);
//if(rst.next()){
while(rst.next()){
dbUser = rst.getString("userName");
dbPsswd = rst.getString("password");
if(!dbUser.equals(userName) && !dbPsswd.equals(password)){
validUser = true;
break;
}else{
validUser = false;
}
}
}catch(SQLException _sqlExp){
_sqlExp.printStackTrace();
}/*finally{
if(rst!=null){
try{
rst.close();
}catch(SQLException sqlexp){}
}if(stat!=null){
try{
stat.close();
}catch(SQLException sqlexp){}
}if(conn!=null){
try{
conn.close();
}catch(SQLException sqlexp){}
}
}*/
return validUser;
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}
aiExa at 2007-7-12 16:43:45 >

# 3
Hey.....u have changed the code....it is not the same code which u pasted the first time.....
see the if check inside the while loop....
it was as following first time when u pasted the code
-
if(dbUser.equals(userName) && dbPsswd.equals(password)){
validUser = true;
}else{
validUser = false;
}
-
and now it is
--
if(!dbUser.equals(userName) && !dbPsswd.equals(password)){
validUser = true;
break;
}else{
validUser = false;
}
-
u have changed the condition check....u have added the not condition (!)
revert it back...or take the whole while loop from my last post...
it should work.....
Hope this helps...
Thanks
# 4
Yea sorry I posted that code. I just wanted to change the condition to see if the method will return true. But even in that case it returns false. Otherwise am using the one posted earlier with the change only after I added break
here is the fragment am using
while(rst.next()){
dbUser = rst.getString("userName");
dbPsswd = rst.getString("password");
if(dbUser.equals(userName) && dbPsswd.equals(password)){
validUser = true;
break;
}else{
validUser = false;
}
}
aiExa at 2007-7-12 16:43:45 >

# 5
Assuming that the username is unique in the database, then the whole while loop would be meaningless. Replace it by if (resultSet.next()) { validUser = true; }. Also a double check on the username and password is completely meaningless as the DB simply doesn't return any row if the username + password combination cannot be found in the DB.
# 6
I will suggest you to run the query independently (i.e in MySql DB ) and check whether it gives u back any data or not...
run the following query...
select * from tblLogin where userName = 'alex' and password = 'alex'
let us know whether u r getting any data or not....
thanks
# 7
ok I have tried....here is the code below but don't seem to get it right. Atleast it resturns true now when I change the condition to if(!dbPsswd.equals(password))
:-)
public boolean authenticate(String userName, String password){
boolean validUser = false;
String jndiDS = "java:comp/env/jdbc/musicClub";
String _sqlQry = "select * from tblLogin where userName = '" + userName + "'";// and password = '" + password + "'";
String dbPsswd;
String dbUser;
Connection conn = null;
Statement stat = null;
ResultSet rst = null;
try{
DAO dao = new DAO();
conn = dao.getDbConnection(jndiDS);
stat = conn.createStatement();
rst = stat.executeQuery(_sqlQry);
//while(rst.next()){
if(rst.next()){
//dbUser = rst.getString("userName");
dbPsswd = rst.getString("password");
if(dbPsswd.equals(password)){
validUser = true;
//break;
}else{
validUser = false;
}
}
}catch(SQLException _sqlExp){
_sqlExp.printStackTrace();
}/*finally{
if(rst!=null){
try{
rst.close();
}catch(SQLException sqlexp){}
}if(stat!=null){
try{
stat.close();
}catch(SQLException sqlexp){}
}if(conn!=null){
try{
conn.close();
}catch(SQLException sqlexp){}
}
}*/
return validUser;
}
aiExa at 2007-7-12 16:43:45 >

# 8
:-) ....gosh the query return nothing......
The problem is I encripted the password.....
alex| *8258F2618980E77E5220ECD7
Could it be the problem?
Sorry this is not the DB forum but the sript I used to insert into my table shows the password is "alex". Here is the script below:
USE musicClub;
DROP TABLE tblLogin;
CREATE TABLE tblLogin(
userId INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
memberId INT UNSIGNED NOT NULL,
userName VARCHAR(20) NOT NULL,
password VARCHAR(25) NOT NULL,
roleId INT UNSIGNED NOT NULL
);
INSERT INTO tblLogin(memberId,userName,password,roleId) VALUES('1','alex',password("alex"),'1');
Thanx.
aiExa at 2007-7-12 16:43:45 >

# 9
Well thank you very much for the help!!! The problem is with the encrypted password...I queried the DB with the password string encrypted in MySql and it worked. Even the code worked as well.Strange for me. Thanx a lot!!!
aiExa at 2007-7-12 16:43:45 >
