Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java & MySQL - Create a login authentication

I have successfully connected my Java app to MySQL, and then I want the user to input their username and password. Then it would send a query to MySQL and look for a spot with that username, and then compare the password given, with the password in the database. And for the most part, this works. Let's say the username is "ABC" and the password is "def". If when prompted for username, and typed "ABC def" it is saying it is successful, same with a password of "def a". I believe the problem is the rs.next(), and it is checking only for any text before a space.

Any ideas for solutions?

    String databaseUsername = "";
    String databasePassword = "";

    // Check Username and Password
    System.out.print("Enter Username: ");
    String name = sc.next();
    System.out.print("Enter Password: ");
    String password = sc.next();

            // Create SQL Query
    Statement stmt = connection.createStatement();
    String SQL = "SELECT * FROM users WHERE users_name='" + name + "' && users_password='" + password+ "'";

    ResultSet rs = stmt.executeQuery(SQL);

            // Check Username and Password
    while (rs.next()) {
        databaseUsername = rs.getString("users_name");
        databasePassword = rs.getString("users_password");
    }

    if (name.equals(databaseUsername) && password.equals(databasePassword)) {
        System.out.println("Successful Login!\n----");
    } else {
        System.out.println("Incorrect Password\n----");
    }
like image 412
Jonathon Charles Loch Avatar asked Oct 22 '22 16:10

Jonathon Charles Loch


1 Answers

If the ResultSet returns a row, the Username and Password have already been checked by the SQL statement. You do not need to check again. Additionally, you should put in place a system where the same Username can not be used more than once. (Make it Unique or key on it in the database)

Also, use prepared statements and hashed passwords to avoid injection and other attacks.

like image 67
PRNDL Development Studios Avatar answered Oct 27 '22 11:10

PRNDL Development Studios