So I've been trying to get my credentials to be validated when I log in to my server. This is the simple set of data I am trying to validate.
(456789, 'Dave123', 'password', 'Dave', 'Davidson', 'dave@dadavid', 2), (123456, 'John456', '123456', 'John', 'Johnson', 'john@jojohn', 1), (456878, 'Kate789', 'abcdef', 'Kate', 'Kateson', 'kate@kitkat', 1)
public class LoginService {
//username and password with id identifier
//0 for false, 1 for employee and 2 for manager
public boolean login(String username, String password, int id) {
try(Connection connection = ConnectionUtil.getConnection()) {
ResultSet resultSet = null; // intialize an empty resultset that will store the results of our query.
//sql statement to get all of the info from reimbursement
String sql = "select * from users where username =? and pass=? and user_role_id=?"
+ "values (?,?,?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(2, username );
preparedStatement.setString(3, password );
preparedStatement.setInt(7, id);
if(username.equals(username) && password.equals(password) && id == (1) ) {
return true;
}
if(username.equals(username) && password.equals(password) && id == (2) ) {
return true;
}
}catch (Exception e) {
// TODO: handle exception
}
return false;
}
}
So when it finishes validating, if the username and password are in the database it would return true. Otherwise, it would return a false, and not let the user log in. But currently, all it does is returning false, and not letting the user log in.
I tried to run this on postman and it would accept the values and would let me log in, but trying this on the live server would reject it.
<input id="username" type="text" placeholder="username" class="col-sm-4 form-control">
<input id="password" type="password" placeholder="password" class="col-sm-4 form-control">
<input id="id" type="number" placeholder ="id" class="col-sm-4 formcontrol">
This is what I have in my html.
preparedStatement.setXxx()calls seem to miss a couple of parameters. I assume you left out those calls but if not you're very likely getting an exception since the query has incomplete parameters. Also,//TODO: handle exceptionis something you should fix first since right now you're swallowing it and thus you don't get any info. At least print the stacktrace if you can't handle it in another way right now. And btw, catch specific exceptions for more specific handling than just logging.username.equals(username) && password.equals(password)basically compares the parameters to themselves and that would always be true (unless one is null and you get a NPE). 3) Instead of comparing the credentials in your code use the query anc check whether it returns something or not. 4) For better security have a look at password hashing and salting or ideally into using an identity provider like Keycloak.