Validation a username and password in c# - c#

I am new to c# and visual studios and i am creating a windows form application that requires a username and password to log in. I have successfully implemented the database to register a user but cannot seem to get the login to work. There is two errors in the code below:
private void btnLogin_Click(object sender, EventArgs e)
{
MySqlConnection con = new MySqlConnection();
con.ConnectionString = "datasource=127.0.0.1;port=3306;username=root;password=;";
Int32 verify;
string query1 = "Select count(*) from Login where Username='" + Username.Text + "' and Password='" + Password.Text + "' ";
MySqlCommand cmd1 = new MySqlCommand(query1, con);
con.Open();
verify = Convert.ToInt32(cmd1.ExecuteScalar());
con.Close();
if (verify > 0)
{
new FormMainMenu().Show();
this.Hide();
}
else
{
MessageBox.Show("Username or Password is Incorrect")
}
}
The Username.Text and the Password.Text are both underlined and says the name
does not exist in the current context.
If anyone has any solutions to this, I would be very grateful. Thanks

you can try this, you just to change the connection to MYSQL Connector.
public int GetScalarValue()
{
int result = 0;
using (SqlConnection cn = new SqlConnection("CONECTION_STRING"))
{
cn.Open();
using (SqlCommand cmd = new SqlCommand("select count(*) from login where username=#login and password=#password")) {
cmd.Parameters.Add("#login", SqlDbType.VarChar).Value = Username.Text;
cmd.Parameters.Add("#password", SqlDbType.VarChar).Value = Password.Text;
result = int.Parse(cmd.ExecuteScalar().ToString());
}
}
return result;
}

Here is a basic and simple approach to validate password, easy to understand if you are beginner level programmer. It checks for min length, digit, lower case, upper case, special characters in input password string.
private bool ValidPass(string pass)
{
bool passLength = false, hasDigit = false, hasUpper = false, hasLower = false, hasSpecialChar = false;
if (pass.Length >= 6)
passLength = true;
foreach (char c in pass)
{
if (char.IsDigit(c))
hasDigit = true;
else if (char.IsUpper(c))
hasUpper = true;
else if (char.IsLower(c))
hasLower = true;
}
string specialChar = "\\/~!##$%^&*()-_+={[]};:'\"|,<.>?";
foreach (char c in specialChar)
{
if (pass.Contains(c))
hasSpecialChar = true;
}
if (passLength && hasDigit && hasUpper && hasLower && hasSpecialChar)
return true;
return false;
}

Related

Invalid Column name 'password'

protected void Button1Login_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["UserThomasConnectionString"].ConnectionString);
conn.Open();
string checkuser = "select count(*) from RegisterFormTable where User_Name='" + TextBox1Username.Text + "'";
SqlCommand com = new SqlCommand(checkuser, conn);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
conn.Close();
if (temp == 1)
{
conn.Open();
string checkPasswordQuery = "select password from RegisterFormTable where User_Name='" + TextBox1Username.Text + "'";
SqlCommand passComm = new SqlCommand(checkPasswordQuery, conn);
string password = passComm.ExecuteScalar().ToString();
password = string.Join("", password.Split(default(string[]), StringSplitOptions.RemoveEmptyEntries));
if (password == TextBox2Password.Text)
{
Session["New"] = TextBox1Username.Text;
Response.Write("Password is correct");
}
else
{
Response.Write("Password is not correct");
}
}
else
{
Response.Write("Username is not correct");
}
conn.Close();
}
string password = passComm.ExecuteScalar().ToString();
This is line code that is error
Please help. what should I do?
using BCrypt.Net; // Add this package via NuGet
protected void Button1Login_Click(object sender, EventArgs e)
{
//Note the different column name. You'll have to change the table to use a hash instead of a raw password!
// You also have to change the user creation and password change code to create the hash values instead of saving the raw text
// THIS IS IMPORTANT!!!
string SQL = "select passwordHash from RegisterFormTable where User_Name= #UserName";
using var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["UserThomasConnectionString"].ConnectionString);
using var com = new SqlCommand(SQL, conn);
// Use the actual column type and length from the database here
com.Parameters.Add("#UserName", SqlDbType.NVarChar, 25).Value = TextBox1Username.Text;
conn.Open();
string hash = com.ExecuteScalar() as string;
if (string.IsNullOrWhitespace(hash))
{
Response.Write("Username is not correct");
}
else if (BCrypt.Verify(TextBox2Password.Text, hash))
{
Session["New"] = TextBox1Username.Text;
Response.Write("Password is correct");
}
else
{
Response.Write("Password is not correct");
}
}

Column 'username' does not belong to table Table

I am trying to do lock user account for Invalid login attempts in Asp.Net C# by using Visual Studio 2019. Database is using MySql Workbench 8.0 CE. But facing the error
C# code shown as below:
using System;
using System.Data;
using MySql.Data.MySqlClient;
namespace Canteen_UAT
{
public partial class LoginDetail : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click1(object sender, EventArgs e)
{
MySqlConnection scon = new MySqlConnection("server = XXX.XXX.XX.XXX; user id = root; password = XXXXX; persistsecurityinfo = True; database = posdbms_uat");
String myquery = "select count(*) from posdbms_uat.logindetail where username='" + TextBox1.Text + "'";
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = myquery;
cmd.Connection = scon;
MySqlDataAdapter da = new MySqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
String uname;
String pass;
String status;
//String lockstatus;
int attemptcount = 0;
if (ds.Tables[0].Rows.Count > 0)
{
uname = ds.Tables[0].Rows[0]["username"].ToString();
pass = ds.Tables[0].Rows[0]["password"].ToString();
status = ds.Tables[0].Rows[0]["status"].ToString();
scon.Close();
if (status == "Open")
{
if (uname == TextBox1.Text && pass == TextBox2.Text)
{
Session["username"] = uname;
Response.Redirect("Order.aspx");
}
else
{
Label2.Text = "Invalid Username or Password - Relogin with Correct Username & Password. No of Attempts Remaining : " + (2 - attemptcount);
attemptcount = attemptcount + 1;
}
}
else if (status == "Locked")
{
Label2.Text = "Your Account Locked Already : Contact Administrator";
}
else
{
Label2.Text = "Invalid Username or Password - Relogin wit Correct Username and Password.";
}
if (attemptcount == 3)
{
Label2.Text = "Your Account Has Been Locked Due to Three Invalid Attempts - Contact Administrator.";
setlockstatus(TextBox1.Text);
attemptcount = 0;
}
}
}
private void setlockstatus(String username1)
{
String mycon = "server = xxx; user id = root; password = xxx; persistsecurityinfo = True; database = posdbms_uat";
String updatedata = "Update posdbms_uat.logindetail set status='Locked' where username='" + username1 + "' ";
MySqlConnection con = new MySqlConnection(mycon);
con.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = updatedata;
cmd.Connection = con;
cmd.ExecuteNonQuery();
}
}
}
Not sure what might be causing this.
What I have tried:
I created a table as posdbms_uat, datatable match the column name in the database table and with appropriate datatype. Not sure how this error pops up.
The query:
String myquery = "select count(*) from posdbms_uat.logindetail where username='" + TextBox1.Text + "'";
...only returns the number of rows matching the WHERE condition - not the actual data in the rows. It should be fixed by specifying the columns you want to get:
String myquery = "select username, password, status from posdbms_uat.logindetail where username='" + TextBox1.Text + "'";
Also, you should consider using parametrization to avoid SQL injection (see this SO question). Another thing is, please do not store the password in plain text.

How can I make my Login Form Object-Oriented

My problem is I don't know how to call the textboxes and buttons to my class from my form login. So I decided to put my codes inside my btnLogin events. How can I make my codes oop style?
private void btnLogin_Click(object sender, EventArgs e)
{
int count = 0;
Connection connection = new Connection();
string sql = "SELECT * FROM tbl_Account WHERE Username='" + txtUserName.Text + "' and Password='" + txtPassword.Text + "'";
MySqlConnection conn = new MySqlConnection(connection.ConnectionString);
MySqlCommand cmd = new MySqlCommand(sql, conn);
conn.Open();
MySqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
count++;
}
if (count == 1)
{
MessageBox.Show("Login Successfully!");
this.Hide();
main.showMeForm4(this);
}
else
{
txtPassword.Focus();
MessageBox.Show("Username or Password Is Incorrect");
txtUserName.Text = "";
txtPassword.Text = "";
}
conn.Close();
}
Put your business logic to a separate class:
Do not concat SQL query (SQL Injections).
BusinessLogic class
public bool Authorize(string userName, string userPassword)
{
Connection connection = new Connection();
string sql = "SELECT Count(*) FROM tbl_Account WHERE Username=#userName and Password=#userPassword";
MySqlConnection conn = new MySqlConnection(connection.ConnectionString);
MySqlCommand cmd = new MySqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#userName",userName);
cmd.Parameters.AddWithValue("#userPassword",userPassword);
int count = 0;
try
{
conn.Open();
int count = int.TryParse(cmd.ExecuteScalar().ToString());
}
finally
{
con.Close();
}
return count==1;
}
Call it:
BusinessLogic businessLogic = new BusinessLogic();
private void btnLogin_Click(object sender, EventArgs e)
{
if (businessLogic.Authorize(txtUserName.Text, txtPassword.Text)
{
MessageBox.Show("Login Successfully!");
this.Hide();
main.showMeForm4(this);
}
else
{
txtPassword.Focus();
MessageBox.Show("Username or Password Is Incorrect");
txtUserName.Text = "";
txtPassword.Text = "";
}
}

using IF condition inside a while loop in C#

I have a problem with my C# code. I have created a login form in C# 2010. When I am validating the user name, I used an if-condition inside the while loop but the thing is that even when the username and password are correct, it executes the else-statement. Please help me to solve this.
Here is my code :
private void btnlogin_Click(object sender, EventArgs e) {
string connection=
#"Data Source=.\SQLEXPRESS;"
+" AttachDbFilename=|DataDirectory|ResturantDB.mdf;"
+" Integrated Security=True; User Instance=True";
SqlConnection cn=new SqlConnection(connection);
try {
cn.Open();
}
catch(Exception) {
// print the exception's message?
MessageBox.Show("Connection to Database failed; check Connection!");
}
SqlCommand cmd=new SqlCommand("SELECT * FROM [Login]", cn);
cmd.Connection=cn;
SqlDataReader reader=null;
reader=cmd.ExecuteReader();
while(reader.Read()) {
if(
txtuser.Text==(reader["Username"].ToString())
&&
txtpass.Text==(reader["Password"].ToString())
) {
//MessageBox.Show( "logged in!" );
Home newhome=new Home();
newhome.Show();
this.Hide();
}
else {
MessageBox.Show("Incorrect credentials!");
}
}
}
you should use a break, when a username is found in your if condition like
bool found = false;
while (reader.Read())
{
if (txtuser.Text == (reader["Username"].ToString()) && txtpass.Text == (reader["Password"].ToString()))
{
//MessageBox.Show("loged in!");
Home newhome = new Home();
newhome.Show();
this.Hide();
found = true;
break;
}
}
if (!found)
MessageBox.Show("Incorrect credentian..!");
you get into the else block because if any login is not correct, the messagebox appears and that is in n-1 cases in your code.
You're checking if all users have the same user name and password. You need to refine your SQL to select only that one user. Also, please read into password hashing for the sake of your users.
Because its in a loop.
create a bool variable. update its value in loop (if found same username and password) and check outside based on its value.
Do this
bool found;
while (reader.Read())
{
if (txtuser.Text == (reader["Username"].ToString()) &&
txtpass.Text == (reader["Password"].ToString()))
{
found = true;
break;
}
}
if (found)
{
MessageBox.Show("loged in!");
Home newhome = new Home();
newhome.Show();
this.Hide();
}
else
{
MessageBox.Show("Incorrect credentian..!");
}
I will solve it on this way:
private void btnlogin_Click(object sender, EventArgs e)
{
string connection = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|ResturantDB.mdf;Integrated Security=True;User Instance=True";
SqlConnection cn = new SqlConnection(connection);
try
{
cn.Open();
}
catch (Exception)
{
MessageBox.Show("Conncetion to Database faild check Connection !");
}
while (true)
{
SqlCommand cmd = new SqlCommand("SELECT [Password] FROM [Login] WHERE [Username] = '" + txtuser.Text + "'", cn);
cmd.Connection = cn;
SqlDataReader reader = null;
reader = cmd.ExecuteReader();
if (!reader.HasRows)
MessageBox.Show("User does not exist. Please, try again.");
else
{
//username should be unique, so only one row is possible to have
reader.Read();
if (txtpass.Text == (reader["Password"].ToString()))
{
//MessageBox.Show("loged in!");
Home newhome = new Home();
newhome.Show();
this.Hide();
return;
}
else
MessageBox.Show("Incorrect credentian..! Try again.");
}
}
}
Simplest and Secure method
SqlCommand cmd = new SqlCommand("Select uname, pswd from [Login] where uname =#uname and pswd =#ps", conn);
cmd.Parameters.Add(new SqlParameter("#uname", "username here"));
cmd.Parameters.Add(new SqlParameter("#ps", "pasword here"));
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
//MessageBox.Show( "logged in!" );
Home newhome = new Home();
newhome.Show();
this.Hide();
}
else
{
MessageBox.Show( "Incorrect credentials!" );
}
No need to loop thru the records for your case
use this query, compate username and password in the query:
"SELECT * FROM [Login] where Username='" + txtuser.Text "' and password = '" + txtpass.Text + "'"

Login is not working

I have written the code below for a login page, but doesn't seem to work.
The variable temp takes a value of 0.
protected void ButtonSbmt_Click(object sender, EventArgs e) {
//if (IsPostBack) {
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegConnectionString"].ConnectionString);
conn.Open();
string cmdstr = "select count(*) from Registration where username='" + TextBoxUsername.Text + "'";
SqlCommand checkuser = new SqlCommand(cmdstr, conn);
int temp = Convert.ToInt32(checkuser.ExecuteScalar().ToString());
if (temp == 1) {
string str = "select password from Registration where username='" + TextBoxUsername.Text + "'";
SqlCommand pass = new SqlCommand(str, conn);
string pass1 = pass.ExecuteScalar().ToString();
conn.Close();
if (pass1 == TextBoxPassword.Text) {
Session["new"] = TextBoxUsername.Text;
Response.Redirect("secure.aspx");
} else {
Label1.Visible = true;
Label1.Text = "invalid password";
}
}
}
Use the ASP.NET membership provider, and the ASP.NET login controls along with ASP.NET forms authentication. This is built-in functionality that ASP.NET provides; it works, it's secure, and you don't have to write the SQL statements and logic.
Lesson one on security - if there is built-in functionality, use it. It will always be better than starting to write your own.

Categories