I am trying to make login where the entered Password and Username is compared with my Database and if they both match you can login.
I just started working with MySQL and BCrypt.
Here is my code so far:
#FXML
void anmeldenButton(ActionEvent event) throws NamingException, ClassNotFoundException {
String myUrl = "jdbc:mysql://localhost:3306/pwmanager?verifyServerCertificate=false&useSSL=true";
Connection conn = null;
username = tfuser1.getText().toString();
try {
conn = DriverManager.getConnection(myUrl, "", "");
query = "SELECT benutzername, passwort FROM nutzer WHERE (benutzername = ? and passwort = ?)";
PreparedStatement ps = conn.prepareStatement(query);
ps.setString(1, username);
ps.setString(2, password);
ResultSet rs = ps.executeQuery();
while (rs.isBeforeFirst()) {
checkUser = rs.getString(1);
checkPass = rs.getString(3);
if (BCrypt.checkpw(pf1.getText(), checkPass) && (checkUser.equals(username))) {
System.out.println("yay");
} else {
System.out.println("ney");
}
}
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
Thanks for your help!
Your code doesn't make much sense.
The entered password can't possibly be equal to the stored password, since the stored password is hashed, and the entered password is not. So you can't use
and passwort = ?
Second, your query selects only two values, but you then use
checkPass = rs.getString(3)
You need to get the stored hashed password from the database thanks to the user name only, and then use Bcrypt to verify that the entered password and the stored hashed password match.
Also,
while (rs.isBeforeFirst())
doesn't make much sense either, and the query is supposed to return 0 or one row. So just use
if (rs.next())
Related
this a login button code in java in NetBeans.
Is there another way to check the equality in database?
what is the while (Rs. Next) do?
Connection conn = null;
ResultSet rs = null;
PreparedStatement pst = null;
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String sql = "select username,password from user Where (username =? and password =? )";
try {
int count = 0;
pst = conn.prepareStatement(sql);
pst.setString(1, txt_username.getText());
pst.setString(2, txt_password.getText());
rs = pst.executeQuery();
{
}
while (rs.next()) {
count = count + 1;
}
if (count == 1) {
JOptionPane.showMessageDialog(null, "Sucess");
MainMenu j = new MainMenu();
j.setVisible(true);
this.dispose();
} else {
JOptionPane.showMessageDialog(null, "Username and Password is not correct");
#
Maybe this helps:
https://1bestcsharp.blogspot.com/2016/08/java-login-form.html
Briefly, if you query a DB with two parameters: username and password and recieve a not empty response - that means the pair username and password is valid.
Another way is needed when you store password in the DB not as a plain text. You can query a password if you store crypted passwords in DB. See the answer to that question Verify BCrypt Hash password when Login
I created a login frame where the user has to enter a username or password. The user credentials are stored in an encrypted format (AES) on a MySQL database. For test purposes when the access button is pressed the frame takes the data entered in the txtUsername and txtPassword, encrypts them and sets the encrypted credentials in the txtEncUName and txtEncPword. The application will then compare the encrypted credentials with the encrypted data in the txtEncUName and txtEncPword textfields.
If the credentials are correct the user is granted access and directed to the respective page depending on if they have admin access or not. If their account has been locked, then they will be notified by a jLabel and access will not be granted. When I tested this earlier, it worked perfectly fine but now here's my problem:
When I try login, the application immediately says that the account is inaccessible. I have checked the credentials and they are correct. No errors come up and the stack trace doesn't come up either.
What can I do to get this to check the credentials properly?
Here is the method used for the access button:
public void loginMethod()
{
String user = txtUsername.getText();
String pwd = new String(txtPassword.getPassword());
try
{
String enc1 = LoginFrame.encrypt(user);
String enc2 = LoginFrame.encrypt(pwd);
encUname.setText(enc1);
encPword.setText(enc2);
String aes1 = encUname.getText();
String aes2 = encPword.getText();
String getAccess = "select * from login_db";
Class.forName("com.mysql.jdbc.Driver");
Connection conn = (Connection)
DriverManager.getConnection("jdbc:mysql://localhost:3306/user_db","root","password");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(getAccess);
if(rs.next())
{
String username = rs.getString("emp_num");
String password = rs.getString("pword");
String access = rs.getString("adminAccess");
String locked = rs.getString("accLocked");
if((aes1.equals(username)) && (aes2.equals(password)) && (access.equals("Yes"))&& ("No".equals(locked)))
{
AdminPage ap = new AdminPage();
ap.setVisible(true);
this.dispose();
}
else if ((aes1.equals(username)) && (aes2.equals(password)) && (access.equals("No"))&& ("No".equals(locked)))
{
EmployeeMainPage emp = new EmployeeMainPage();
emp.setVisible(true);
this.dispose();
}
else if((aes1.equals(username)) && (aes2.equals(password)) && (access.equals("Yes"))&& ("Yes".equals(locked)))
{
lblWrongLogin.setVisible(true);
lblWrongLogin.setText("Account inaccesible, please contact admin for support.");
}
else if((locked.equals("Yes")))
{
lblWrongLogin.setVisible(true);
lblWrongLogin.setText("Account inaccessible, please contact admin for support.");
}
}
}
catch (Exception e)
{
JOptionPane.showMessageDialog(this, e);
}
}
}
String getAccess = "select * from login_db";
The query above selects all rows from the database, but the code...
if(rs.next())
...only checks if the first row matches - there will be issues if there is more than a single row. Consider changing the query to look for matches to username and password
PreparedStatement ps = conn.prepareStatement( "select * from login_db where emp_num=? AND pword=?");
ps.setString(1, aes1);
ps.setString(2, aes2);
ResultSet rs = ps.executeQuery();
if ( rs.next() ){
//logic here
}
public int addUsers(int USER_ID,String FIRST_NAME,String LAST_NAME,String PASSWORD,String USERNAME,String USER_PERMISSION) throws SQLException {
Connection conn = null;
conn = getConnectivity(conn) ;
getConnectivity(conn);
String sqlSelect = "SELECT * from USER_DETAILS";
PreparedStatement pres = conn.prepareStatement(sqlSelect);
ResultSet rs1 = pres.executeQuery();
if(rs1.next()){
String Username = rs1.getString(5);
System.out.println("username found "+Username);
System.out.println("username input " + USERNAME);
System.out.println("password input " + PASSWORD);
if (Username.equals(USERNAME)){
System.out.println("Username already exists");
conn.close();
}
else{
System.out.println("FOUND ELSE");
String sql = "INSERT INTO USER_DETAILS VALUES (?,?,?,?,?,?)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, USER_ID);
ps.setString(2, FIRST_NAME);
ps.setString(3,LAST_NAME);
ps.setString(4,PASSWORD);
ps.setString(5,USERNAME);
ps.setString(6,USER_PERMISSION);
int result = ps.executeUpdate();
System.out.println(result);
}
}
conn.close();
return USER_ID;
}
and for login I am using
public boolean login(String USERNAME, String PASSWORD) throws SQLException
{
boolean result = false;
Connection conn = null;
conn = getConnectivity(conn) ;
String sqlSelect = "SELECT * from USER_DETAILS";
PreparedStatement pres = conn.prepareStatement(sqlSelect);
ResultSet rs1 = pres.executeQuery();
if(rs1.next()){
String Username = rs1.getString(5);
String Password = rs1.getString(4);
String UserPermission = rs1.getString(6);
System.out.println("username found "+Username);
System.out.println("username input " + USERNAME);
System.out.println("password input " + PASSWORD);
if (Username.equalsIgnoreCase(USERNAME) && Password.equalsIgnoreCase(PASSWORD) && UserPermission.equalsIgnoreCase("blocked")){
System.out.println("User Logged in");
conn.close();
}
System.out.println("gets out of the code");
}
conn.close();
return result;
}
first of all it is allowing to enter more than one entry, so duplicates occurring regardless of my if statement, and when i add fresh new data and try to see I can log in, it still compares with previously added data and does not work. Can someone see what am i doing wrong here. please thanks
below is the system print out i get ,
Connection Valid
username found kamran (don't know why he is still picking up this column)
username input macbook (these i have already in my database)
password input hello (these i have already in my database)
gets out of the code
Connection Valid
Connection Valid
username found kamran (don't know why he is still picking up this column)
username input macho (these i have already in my database)
password input hello (these i have already in my database)
FOUND ELSE (dont know why it adds data when they already exist in database)
1
Your code doesn't make sense: you are querying for all users and only checking the first returned user if it matches. Of course that is going to fail if the first returned user doesn't match: in addUsers you will try to add the user if the first user returned doesn't match, in login a user can only login if it is the first user.
You need to use a WHERE clause to only request the user you want to check:
// Note: this assumes a case insensitive collation
String sqlSelect = "SELECT * from USER_DETAILS WHERE username = ?";
try (PreparedStatement pres = conn.prepareStatement(sqlSelect)) {
pres.setString(1, USERNAME);
try (ResultSet rs1 = pres.executeQuery()) {
if (!rs1.next) {
// user doesn't exist yet, create...
}
}
}
You need to do something similar for login (but then with if (rs1.next()) instead).
There are more problems with your current code: you are storing plaintext passwords: you should really hash them with a strong password hash like PBKDF2. Also please follow the java naming conventions. Variables and parameters are camelcase so not USERNAME but username (or userName), not UserPermission, but userPermission. This improves the readability for people who are used to the java naming conventions.
How do I validate a certain email and password while an user logs in?
protected void doPost(HttpServletRequest request, HttpServletResponse res) throws IOException, ServletException {
String email=request.getParameter("email");
String pass=request.getParameter("pass");
OutputStream out = res.getOutputStream();
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:8080/college", "root", "root");
Statement st=con.createStatement();
String strSQL = "SELECT email,password FROM student";
How do I continue after the SELECT statement? I would prefer using the if...else statement to do the validation.
First close all connection resources properly - use a Java 7 try-with-resources.
Here is an simple example:
final String email = request.getParameter("email");
final String pass = request.getParameter("pass");
try (final Connection con = DriverManager.getConnection("jdbc:mysql://localhost:8080/student", "root", "root");
final PreparedStatement statement = con.prepareStatement("SELECT COUNT(*) AS count FROM student WHERE email=? AND password=?");) {
statement.setString(1, email);
statement.setString(2, pass);
try (final ResultSet resultSet = statement.executeQuery()) {
if (resultSet.next()) {
final int rows = resultSet.getInt("count");
if (rows > 1) {
throw new IllegalStateException("More than one row returned!");
}
boolean validUser = rows == 1;
}
}
}
But really you should hash passwords in the database. Use something like jBcrypt. Your code would then look like:
final String email = request.getParameter("email");
final String pass = request.getParameter("pass");
try (final Connection con = DriverManager.getConnection("jdbc:mysql://localhost:8080/student", "root", "root");
final PreparedStatement statement = con.prepareStatement("SELECT pass FROM student WHERE email=?");) {
statement.setString(1, email);
statement.setString(2, pass);
try (final ResultSet resultSet = statement.executeQuery()) {
if (resultSet.next()) {
final String hash = resultSet.getString("pass");
final boolean valid = BCrypt.checkpw(pass, hash);
}
}
}
Obviously you need to add error checking if there are no rows returned from the query. You also need to check that only one row is returned. But I leave that as an exercise.
you can use if, if you like. Use the input as your where statement and then check to see if there is a match, error or null, then execute whatever you want it to do.
You can use email and password in the SQL statement itself. like:
SELECT email, password from student where email = ? and password = ?
prepare above statement and bind the parameters.
This way validation will be done on the DB and you just need to check the result count (which has to be 1). You should have index on email column to have better SQL performance.
Do you relay need to fetch all students?
PreparedStatement st = con.prepareStatement("SELECT count(*) FROM student WHERE email=? AND password=?");
st.setString(1, email);
st.setString(2, pass);
ResultSet rs = st.executeQuery();
rs.next();
int count = rs.getInt(1);
if (count == 1) {
// password and email are correct
}
For this answer, I'll assume that by "validate email and password", what you mean is you want to authenticate the user based on their email address and a password. And not that you want to check whether the email address is a real email address.
So, the first thing you need to do is encrypt the passwords in your database, using a hash algorithm and a random salt. You record the salt alongside the hashed password.
Next thing is, when the user logs in, you look up the salt for that user, and you perform the same hash with the salt. Then you compare the result of that with the previously saved password hash, and if they're the same, then the passwords were the same.
It's important that the salt be random and different for every user.
Plenty of reading to be found on the above terms on the Internets.
Once you've done that, you should also apply the very sensible suggestions in other answers to only select the user you want, and handle your resources correctly.
WARNING I am not an expert on security, and neither are you. If you're implementing a log-in system for an exercise, fine. If it's for the real world, use something that's been written by someone who knows what they're doing.
I am working on a project to create a login page. To do this I am using a database to store the user information. As of right now there are four columns in my database: username, password, email, and admin.
Right now I am having a problem accessing that database using a prepared statement/Result set format. Right now I get to the third return, print out the imputed username and password then generate an error. Am I formatting my prepared statement incorrectly?
Okay, based of previous answers I have corrected most of my code(thank you) and now I have this error when I am trying to print out of the result set:
java.sql.SQLException: Column Index out of range, 2 > 1.
any ideas?
My code:
Properties props = new Properties();
props.setProperty("user", "root");
props.setProperty("password", "root");
props.setProperty("databaseName", "dbname");
String ret = ERROR;
Connection myCon = null;
try{
System.out.println("got here 1!");
Class.forName ("com.mysql.jdbc.Driver").newInstance();
System.out.println("got here 2!");
myCon = DriverManager.getConnection("jdbc:mysql://ipaddresshere:3306/dbname",props);
System.out.println("got here 3!");
System.out.println(username);
System.out.println(password);
String dbQuery = "SELECT count(*) FROM loginTestTable where username = "+username+" AND password = "+password+"";
//PreparedStatement prep = myCon.prepareStatement(dbQuery);"
PreparedStatement ps = myCon.prepareStatement(dbQuery);
ps.setString(1, username);
ps.setString(2, password);
ResultSet result = ps.executeQuery();
System.out.println("got here 4!");
while (result.next()) {
System.out.println("got here 5!");
ret = SUCCESS;
System.out.println("username: "+result.getString(1)+" password: "+result.getString(2)+" email: "+result.getString(3));
if(result.getString(4).toLowerCase()=="YES"){
ret = "admin";
}
}
}catch(Exception e){
System.out.println("arg there be an error me matey!");
ret = ERROR;
}finally{
if(myCon!=null){
try{
myCon.close();
}catch (Exception e){
}
}
}
return ret;
There are multiple problems with your code:
First, you're missing quotes around username and password.
String dbQuery = "SELECT count(*) FROM loginTestTable " +
"where username = '"+username+"' AND password = '"+password+"'";
Second, the PreparedStatement#setString() methods have no effect unless you define your query with place holders ? like
String dbQuery = "SELECT count(*) FROM loginTestTable " +
"where username = ? AND password = ?";
Third, you must never compare strings with equality == operator. Use String.equals() as
// also note you need toUpperCase() here
"YES".equals(result.getString(4).toUpperCase());
Change the line:
String dbQuery = "SELECT count(*) FROM loginTestTable where username = "+username+" AND password = "+password+"";
By:
String dbQuery = "SELECT count(*) FROM loginTestTable where username = ? AND password = ?";