0

I'm using JDBC to check a database for a username and password to grant login access to my gui, but when I'm trying to test that the JDBC is working its not blocking access when the wrong username and password is entered..

Below is my code, I believe its connecting the the database correctly, as when i press the login button it outputs Running Check Login and User is validated.

class usernamecheck {

    static final String DATABASE_URL = "jdbc:mysql://localhost:3306/mysql";
    static final String USERNAME = "root";
    static final String PASSWORD = "root";

   // launch the application
    public static boolean checkLogin(String username, String password)
            throws SQLException {
        System.out.print("Running Check Login \n");

        Connection connection = null; // manages connection
        PreparedStatement pt = null; // manages prepared statement

        // connect to database usernames and query database
        try {

            // establish connection to database
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            Connection con = DriverManager.getConnection(DATABASE_URL, "root", "root");

            // query database
            pt = con.prepareStatement("select userName,password from mysql.person where userName=?");

            // process query results
            pt.setString(1, username);
            ResultSet rs = pt.executeQuery();
            String orgUname = "", orPass = "";
            while (rs.next()) {
                orgUname = rs.getString("userName");
                orPass = rs.getString("password");
            } //end while
            if (orPass.equals(password)) {
                //do something
                return true;
            } else {
                //do something
            }
        }//end try
        catch (Exception e) {
        } //end catch  
        return false;
    } //end main
}

Code with GUI

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;


public class Login extends JFrame {

    private JTextField jtfUsername, jtfPassword;
    private JButton backButton, loginButton;
    private JMenuItem jmiLogin, jmiBack, jmiHelp, jmiAbout;

    Login() {
        //create menu bar
        JMenuBar jmb = new JMenuBar();

        //set menu bar to the applet
        setJMenuBar(jmb);

        //add menu "operation" to menu bar
        JMenu optionsMenu = new JMenu("Options");
        optionsMenu.setMnemonic('O');
        jmb.add(optionsMenu);

        //add menu "help"
        JMenu helpMenu = new JMenu("Help");
        helpMenu.setMnemonic('H');
        helpMenu.add(jmiAbout = new JMenuItem("About", 'A'));
        jmb.add(helpMenu);

        //add menu items with mnemonics to menu "options"
        optionsMenu.add(jmiLogin = new JMenuItem("Login", 'L'));
        optionsMenu.addSeparator();
        optionsMenu.add(jmiBack = new JMenuItem("Back", 'B'));

        //panel p1 to holds text fields
        JPanel p1 = new JPanel(new GridLayout(2, 2));
        p1.add(new JLabel("Username"));
        p1.add(jtfUsername = new JTextField(15));
        p1.add(new JLabel("Password"));
        p1.add(jtfPassword = new JPasswordField(15));

        //panel p2 to holds buttons
        JPanel p2 = new JPanel(new FlowLayout());
        p2.add(backButton = new JButton("Back"));
        p2.add(loginButton = new JButton("Login"));

        //Panel with image??????

        //add panels to frame
        JPanel panel = new JPanel(new GridLayout(2, 1));
        panel.add(p1, BorderLayout.CENTER);
        panel.add(p2, BorderLayout.SOUTH);
        add(panel, BorderLayout.CENTER);
        setTitle("Main Page");


        //listners for exit menuitem and button
        jmiBack.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Welcome welcome = new Welcome();
                welcome.setVisible(true);
                welcome.setSize(500, 500);
                welcome.setLocationRelativeTo(null);
                registerInterface regFace = new registerInterface();
                regFace.setVisible(false);
                Login.this.dispose();
                Login.this.setVisible(false);
            }
        });

        backButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Welcome welcome = new Welcome();
                welcome.setVisible(true);
                welcome.setSize(500, 500);
                welcome.setLocationRelativeTo(null);
                registerInterface regFace = new registerInterface();
                regFace.setVisible(false);
                Login.this.dispose();
                Login.this.setVisible(false);
            }
        });

        //listner for about menuitem
        jmiAbout.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(null,
                        "This is the login panel"
                        + "\n Assignment for University",
                        "About", JOptionPane.INFORMATION_MESSAGE);
            }
        });

        //action listeners for Login in button and menu item
        loginButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    usernamecheck.checkLogin(jtfUsername.getText(), jtfPassword.getText()); {
                    System.out.println("User is validated");
               }
                } catch (SQLException se) {
                }
                MainMenu mainmenu = new MainMenu();
                mainmenu.setVisible(true);
                mainmenu.setSize(500, 500);
                mainmenu.setLocationRelativeTo(null);
                registerInterface regFace = new registerInterface();
                regFace.setVisible(false);
                Login.this.dispose();
                Login.this.setVisible(false);
            }
        });

        jmiLogin.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                MainMenu mainmenu = new MainMenu();
                mainmenu.setVisible(true);
                mainmenu.setSize(500, 500);
                mainmenu.setLocationRelativeTo(null);
                registerInterface regFace = new registerInterface();
                regFace.setVisible(false);
                Login.this.dispose();
                Login.this.setVisible(false);
            }
        });
    }

    public static void main(String arg[]) {
        Login frame = new Login();
        frame.setSize(500, 500);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}
class usernamecheck {

    static final String DATABASE_URL = "jdbc:mysql://localhost:3306/mysql";
    static final String USERNAME = "root";
    static final String PASSWORD = "root";


   // launch the application
    public static boolean checkLogin(String username, String password)
            throws SQLException {
        System.out.print("Running Check Login \n");

        Connection connection = null; // manages connection
        PreparedStatement pt = null; // manages prepared statement
        Statement stmt = null;
        String query="select userName from person where userName = ? and password = ?";


        // connect to database usernames and query database
        try {

            // establish connection to database
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            Connection con = DriverManager.getConnection(DATABASE_URL, "root", "root");

            // query database
            pt = con.prepareStatement("select userName from person where userName = ? and password = ?");
           
            // process query results
            pt.setString(1, username);
            ResultSet rs = pt.executeQuery(query);
            String orgUname = "", orPass = "";
            while (rs.next()) {
                orgUname = rs.getString("userName");
                orPass = rs.getString("password");
            } //end while
            if (orPass.equals(password) && orgUname.equals(username)) {
                //do something
                return false;
            } else {
                //do something
                return true;
            }
        }//end try
        catch (Exception e) {
        } //end catch  
        return true;
    } //end main
}
5
  • Swallowing exceptions is not a good practice. Commented Sep 27, 2013 at 17:10
  • This code looks to be working as expected (except that you could use if(rs.next() instead of while). Probably your problem is how you present your GUI to user. Commented Sep 27, 2013 at 17:10
  • @LuiggiMendoza updated code with my gui. Commented Sep 27, 2013 at 17:31
  • What is this line if (orPass.equals(password) && orgUname.equals(username)) { when they are both equal you return false, should't it be otherway ?? Commented Sep 27, 2013 at 17:47
  • @SachinThapa I was switching them around to see if they would change anything, they were true to begin with, but im not seeing any changes.. Commented Sep 28, 2013 at 4:04

5 Answers 5

2

Here is some advice:

Do NOT store passwords in the database. Store an MD5 hash of it, then have your Java code or Mysql function convert the user's password input text to an MD5 hash, and then compare that with what's stored in your person table.

Example using Java to do the hashing:

person table:

+----+------------+----------------------------------+
| id | username   | pwhash                           |
+----+------------+----------------------------------+
|  1 | bob        | 9ae4f6963062ba8c77db69aa1f821310 | 
|  2 | ryan       | 3f6af9632621a8ce7d00aa122e2d1310 | 
+----+------------+----------------------------------+

Java code:

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

....

String username = ... // from UI input
String plaintext_password = ... // from UI input

String pwhash_from_passwd = makePwHash(username, plaintext_password);

String pwhash_from_db = ...   // SELECT pwhash FROM person WHERE userName=?

if (pwhash_from_db.equals(pw_hash_from_passwd)) {
    // user is authenticated
} else {
    // invalid username or password
}

...



protected static String makePwHash(String username, String plaintext_password) {
    MessageDigest mdigest=null;
    try {
        mdigest = MessageDigest.getInstance("MD5");
        String dbs = username + plaintext_password;
        byte mdbytes[] = mdigest.digest(dbs.getBytes());
        return toHexString(mdbytes);
    } catch (NoSuchAlgorithmException e) { }
    return null;
}



private static final char[] toHex = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

/**
 * convert an array of bytes to an hexadecimal string
 * @return a string (length = 2 * b.length)
 * @param b bytes array to convert to a hexadecimal string
 */
public static String toHexString(byte b[]) {
    int pos = 0;
    char[] c = new char[b.length*2];
    for (int i=0; i< b.length; i++) {
        c[pos++] = toHex[(b[i] >> 4) & 0x0F];
        c[pos++] = toHex[b[i] & 0x0f];
    }
    return new String(c);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Amen, brother. +1. Worthwhile to mention salting, too.
Thanks for this, I'll probably implement this once I get my current issue solved.
0

I can see one problem when provided password="" and there is will be no record found in that case the following code will return true

if (orPass.equals(password))  // when password =""

Comments

0

This is not good JDBC code. I hope you aren't planning to use this code in production.

Here are just a few of the many things that are wrong with it:

  • Hard coded driver, URL, and credentials. Should be set up in connection pool, external to the app.
  • Empty catch block.
  • Doesn't close Connection, Statement, or ResultSet.
  • No application should have root access to a database. You should create an application ID and GRANT only those permissions needed to accomplish the task.

Comments

0

A few side observations:

1: The comment below isn't correct, the function doesn't (or shouldn't) launch the application. It should only validate the username and password and return true/false. Launching the application should be in its own function (a function should do one thing).

// launch the application

public static boolean checkLogin(String username, String password)

2: you should use a try/catch/finally block to get a connection, preparedStatement, and resultSet. then close them (checking for null first) in reverse order in the finally block, usually all in the same function.

3: Connection pools (dataSource) should be used and the dataSource for the application should be implemented once for the duration of the running application. Using the pool, the connection should be obtained, used, and closed (returned to the pool) as fast as possible.

Comments

0

Your method will return true if you enter a non existing user and an empty password. So in that case it is not blocking access. To avoid this you need to validate that the user exists also.

Here is an example. You might not want to do it exactly like this but you should get the idea.

if (rs.next() && password.equals(rs.getString("password"))) {
    // do something
    return true;
} else {
    //do something
}

Also when you call the checkLogin method from the ActionListener you are not checking the return value so you are not really validating anything. You could do something like this

if (usernamecheck.checkLogin(jtfUsername.getText(), jtfPassword.getText())) {
    // User validated
} else {
    // Not validated
}

6 Comments

so adding orgUname.equals(username) to that if statement fix up the issue?
Actually then somebody could log in with empty username and empty password. Not good.
You could check that the databse query actually returns something. If it returns 0 rows, then the user does not exist.
If you can show me an example, that would be great, I'm completely lost, I'm going to call it a night and try and finish it tomorrow.
Cheers for the example, so that allows users with matching passwords access?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.