简体   繁体   中英

How to verify correctness of login/password JDBC

I'm creating very simple ATM machine. I have MySQL DB with columns like: loginID, password, money. I would like to change my method which can verify correctness of login and password at the beginning (and after this do something). So If login and password are correct, then I want to receive a message "Login successful" or Login unsuccessful". Right now I always have message "Login successful". How can I change it?

    public static void post () throws Exception{

    Scanner sc = new Scanner(System.in);
    System.out.println ("please enter user id:");
    String userId = sc.nextLine();
    System.out.println("please enter password:");
    String pass = sc.nextLine();
    System.out.println("how much you want to put");
    int money = sc.nextInt();

    try {
        Connection con = ConnectionDB.getConnection();
        String sql = "UPDATE `BankDB`.`Info` SET `Money`= ? WHERE `ClientID`= ? AND `ClientPass` = ?";

        PreparedStatement posted = con.prepareStatement(sql);
        posted.setInt(1, money);
        posted.setString(2, userId);
        posted.setString(3, pass);


        posted.executeUpdate();
        con.close();
    } catch (Exception e) {
        e.printStackTrace();
    } finally{
        System.out.println("Login was succesful");
    }
}

If my understanding of the question is valid, you need to check that update command really updated something in DB. In this case you need to get result from posted.executeUpdate() . If it is greater than zero, update updated record in DB and user name / password were correct.

UPDATE queries work even if their WHERE clauses choose zero rows. So your query

 UPDATE `BankDB`.`Info` SET `Money`= ? WHERE `ClientID`= ? AND `ClientPass` = ?

doesn't do anything if either part of the WHERE clause matches nothing. But it still succeeds.

Generally you want to do something like shown in this outline.

  1. SELECT id, password FROM Info WHERE ClientId = ?
  2. Check the password for a match with the one provided by your web user. If it doesn't match, reject the transaction.
  3. UPDATE Info SET Money = Money + ? WHERE id = ? giving the id value you retrieved in the first step.

DANGER your way of validating the user's password is incredibly dangerous in a world infested with cybercriminals. Storing plain-text passwords in a dbms is notorious for being the worst thing you can do about security. This is about password hashing in php, but its advice is valid for any language. Please read it. http://php.net/manual/en/faq.passwords.php Don't reinvent the flat tire in the area of password security. Please.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM