How to validate Password and Username for website in c# - c#

I have a simple login website, which is my first website project in Visual Studio 2015. I have successfully created a SQL database which contains user information like Username, Password, Email and Country, and I have also successfully created a user registration page where a new user can input there details and these details will be added to the database. This all works fine.
but I have hit a roadblock while attempting to validate the Username and Password against the stored values in the row containing the User data in the SQLdatabase to give the user access to the member only pages.
Heres my code snippet for when the user click the login button.
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MembersConnectionString"].ConnectionString);
con.Open();
string checkUser = "SELECT * FROM Members where Username= '" + TextBoxSignUser.Text + "' and Password= '" + TextBoxSignPass.Text + "'";
SqlCommand cmd = new SqlCommand(checkUser, con);
cmd.ExecuteNonQuery();
con.Close();
I know what I need to do is probably something like this pseudocode below, but I am unsure how to go about validating this information against stored values in the database.
if ("Username" and "Password" == the value of Username and Password TextBox.Text)
{
Response.Write("Sign in successful");
Response.Redirect("MemberTestPage.aspx");
}
else
{
Response.Write("Details incorrect, Please try again")
}

Fill the data-table using data adapter one you get the data into a data-table you can get the return values of the query and match the parameters
DataTable Dt = new Datatable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
if (dt.rows.count > 0 )
{
//MATCH FOUND
}

You can use like..
string query= "SELECT * FROM Members where Username= 'usr' and Password= 'pwd'";
SqlCommand cmd = new SqlCommand(query, con);
MySqlDataAdapter objda = new MySqlDataAdapter(cmd);
DataSet objDs = new DataSet();
objda.Fill(objDs);
if(objDs.Tables[0].Rows.Count>0)
{
Response.Write("Sign in successful");
Response.Redirect("MemberTestPage.aspx");
}

You could do as following without using Datasets,
var con = new SqlConnection("your connection string goes here");
SqlCommand cmd = new SqlCommand("SELECT * FROM Members where Username= 'usr' and Password= 'pwd'", con);
bool result = false;
cmd.Connection.Open();
using (cmd.Connection)
{
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
result = true;
}
if (result == true)
// Login successful
else
// Login failed

string query = string.Format("SELECT TOP 1 * FROM [Table] WHERE Username = '{0}' and Password = '{1}'", txtUsername.Text, txtPassword.Text);
command = new OleDbCommand(query, con);
var reader = command.ExecuteReader();
if (reader.HasRows)
{
//successfully login
}
else
//error message

I think first of all it is better to use ADO.NET libraries for some reasons like best performance and high security. Here is my suggestion. hope to be useful for you:
using System.Data.SqlClient;
...
string conStr = ConfigurationManager.ConnectionStrings["MembersConnectionString"].ConnectionString;
string sql = "SELECT * FROM Members where Username = #user and Password = #pass";
SqlParameter pUser = new SqlParameter("#user", TextBoxSignUser.Text);
SqlParameter pPass = new SqlParameter("#pass", TextBoxSignPass.Text);
using (SqlConnection con = new SqlConnection(conStr))
{
using (SqlCommand cmd = new SqlCommand(sql, con))
{
cmd.Parameters.Add(pUser);
cmd.Parameters.Add(pPass);
con.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
// Successfully signed in
// Also you can access your fields' value using:
// 1. its index (e.x. reader[0])
// 2. or its name: (e.x. reader["Username"])
}
else
{
// Login failed
}
}
}
}

Related

how to check the username exist in database or not

This is my code
I don't know what's my fault but it is not checking whether the username exist in database or not.
String connectionString = #"Data Source=localhost; Database=pramod; User ID=itesuser; password=ites; Port=3309;";
MySqlConnection con = new MySqlConnection(connectionString);
con.Open();
String query = "select * from logins where USERNAME=#username and PASSWORD=#password";
MySqlCommand cmd = new MySqlCommand(query, con);
cmd.Parameters.AddWithValue("#username", TextBox1.Text.Trim());
cmd.Parameters.AddWithValue("#password", TextBox2.Text.Trim());
MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
int i = (int)cmd.ExecuteScalar();
if (i == 0)
{
Response.Write("username wrong");
}
if (dt.Rows.Count > 0)
{
Session["username"] = TextBox1.Text.Trim();
Response.Redirect("Dashboard.aspx");
}
else {
Label1.Visible = true;
Label1.Text = "Your password is incorrect";
Label1.ForeColor = System.Drawing.Color.Red;
}
con.Close();
it is checking whether the password is correct or wrong but not the username, now i need to check username and the the password
I think your clue is here:
String query = "select * from logins where USERNAME=#username and PASSWORD=#password";
By doing this, you check the username and password at the same time. So if the username OR the password is incorrect, you get 0 rows in your result.
To get what your want, only mention the username in the SQL query, and if you get a record, you compare the password in .Net code.
So:
String query = "select * from logins where USERNAME=#username";
MySqlCommand cmd = new MySqlCommand(query, con);
cmd.Parameters.AddWithValue("#username", TextBox1.Text.Trim());
MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
And then check the password if you get 1 row back.
This looks like an insecure way of handling logins, so I hope you at least will hash and salt the passwords. Now you are one database leak away from a very embarasing situation. https://duckduckgo.com/?q=password+hashing+and+salting

getting specified value from SQL table based on current user login to Full name

I have below data in SQL query, and am showing the current user "Domain" logged in I want to show the full name in label based on each user using the Windows form,
I got stuck here, how I can continue to find the value
string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
label1.Text = userName.ToUpper();
SqlConnection con = new SqlConnection("Data Source=127.0.0.1;Initial Catalog=db;User ID=AAA;password=******");
con.Open();
string command7 = "SELECT distinct [fullname] ,[Group] ,[Domain] FROM [tableA] where fullname is not null and [group] is not null and [Domian] = '"+ label1.Text + "'";
SqlCommand da7 = new SqlCommand(command7, con);
Full name
Group
Domain
Alex Sam J
A GROUP
test\Alex
Jon Pete F
B GROUP
test\Jon
You can get the value of full name this way :
...
SqlCommand cmd = new SqlCommand(command7, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
labelFullName.Text = da.Tables[0].Rows[0]["fullname"].ToString();
I solve it like this, thanks
SqlCommand cmd = new SqlCommand(da7, con);
cmd.CommandType = CommandType.Text;
//con.Open();
SqlDataReader reader = cmd.ExecuteReader();
//DataTable dt7 = new DataTable();
while (reader.Read())
{
label21.Text = reader["Technician"].ToString();
}
con.Close();

Invalid user credentials in MySQL parameterized query

It shows invalid user credentials even though I inputted the right one. I don't know if I made the parameters wrong or if my query is wrong. I want to learn about parameterized queries but I don't know what I'm doing wrong here.
con.OpenConnection();
using (con.connection)
{
String query = "SELECT * FROM tblUser WHERE Username = #Username and Password = #Password";
try
{
MySqlCommand cmd = new MySqlCommand(query, con.connection);
cmd.Parameters.Add("#Username", MySqlDbType.VarChar).Value = txtUsername.Text;
cmd.Parameters.Add("#Password", MySqlDbType.VarChar).Value = txtPassword.Text;
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
i = Convert.ToInt32(dt.Rows.Count.ToString());
if (i == 0)
{
MessageBox.Show("Invalid user credentials.");
}
else
{
//Do stuff
}
}
catch (MySqlException mse)
{
MessageBox.Show(mse.Message);
}
finally
{
con.CloseConnection();
}
Not sure why it is not working but if you use AddWithValue, it will work. Something like this
cmd.Parameters.AddWithValue("#Username", txtUsername.Text);
cmd.Parameters.AddWithValue("#Password", txtPassword.Text);
Change your code so that it's calls a method, when you click on a Button, pass the Username and Password variable into this Method. Create a AutoProperty for UserName and Password at the Class Level
private DataTable PopulateSomeDatatSet(DataSet aDataset, string UserName, string Password)
{
var query = "SELECT * FROM tblUser WHERE Username = #Username and Password = #Password";
MySqlDataAdapter sda;
using (SqlConnection connStr = new SqlConnection(ConnString)) //replace with your ConnectionString Variable
{
using (MySqlCommand cmd = new MySqlCommand(query, connStr))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#Username", MySqlDbType.VarChar).Value = UserName;
cmd.Parameters.Add("#Password", MySqlDbType.VarChar).Value = Password;
sda = new MySqlDataAdapter(cmd);
new MySqlDataAdapter(cmd).Fill(aDataset);
}
}
((IDisposable)sda).Dispose();
return aDataset.Tables[0];
}

How to extract individual column data from C# MySQL query?

How can I extract the column data from my user row? EX: This gets called on my WCF server when the client logs in. It works up to var xx = ds.Tables[0].Rows[1]; where it throws an error on the clients side. Basically I am trying to have the user/pass verified in the database. Then return to the Client a DateTime of when his subscription expires.
public bool Authenticate(string userId, string password, out string token)
{
token = "";
string MyConnectionString = "Server=localhost;Database=testdb;Uid=root;Pwd=admin;";
MySqlConnection sqlCon = new MySqlConnection(MyConnectionString);
sqlCon.Open();
MySqlCommand cmd = sqlCon.CreateCommand();
cmd.CommandText = "SELECT * FROM table1 WHERE username = '"+userId+"' AND password = '"+password+"'";
MySqlDataAdapter adap = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
adap.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
token = Guid.NewGuid().ToString();
var xx = ds.Tables[0].Rows[0];
CustomDataSource.AddUserData(token, userId);
return true;
}
return false;
}
Well I suppose that your query returns only one row (if it finds the user with the correct password)
In that case you get the date from the first row returned (index zero).
Also I assume that your date is stored in the fifth column (index four), if not you should adjust the second index to point to the correct column. (The base array index is always zero)
if (ds.Tables[0].Rows.Count > 0)
{
token = Guid.NewGuid().ToString();
var xx = ds.Tables[0].Rows[0][4];
CustomDataSource.AddUserData(token, userId);
return true;
}
Said that, let me point to a big problem of this code.
This code could be easily used for a Sql Injection Attack because it concatenates strings, probably typed by your user, to form a Sql Text passed to the database engine. Instead you should use parameters to avoid the Sql Injection problem and the quoting of user text (password with an apostrophe?)
using(MySqlConnection sqlCon = new MySqlConnection(MyConnectionString))
{
sqlCon.Open();
MySqlCommand cmd = sqlCon.CreateCommand();
cmd.CommandText = "SELECT * FROM table1 WHERE username = ?user AND password = ?pwd";
cmd.Parameters.AddWithValue("?user", userId);
cmd.Parameters.AddWithValue("?pwd", password);
using(MySqlDataAdapter adap = new MySqlDataAdapter(cmd))
{
DataSet ds = new DataSet();
adap.Fill(ds);
}
}
var xx = ds.Tables[0].Rows[0].ItemArray[5];
Is how.
try using foreach loop
foreach (DataRow row in ds.Tables[0].Rows)
{
var xx = row[1];
var x = row[5];
// other codes
return true;
}
one more thing, parameterized your query to avoid SQL injection
using(MySqlConnection sqlCon = new MySqlConnection(MyConnectionString))
{
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.Connection = sqlCon;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM table1 WHERE username = #user AND password = #pass";
cmd.Parameters.AddWithValue("#user", userId);
cmd.Parameters.AddWithValue("#pass", password);
using (MySqlDataAdapter adap = new MySqlDataAdapter(cmd))
{
try
{
DataSet ds = new DataSet();
adap.Fill(ds);
}
catch (MySqlException e)
{
// do something with the exception
// don't hide it!
}
}
}
}

C# mysql Execute Reader with parameters Input string was not in a correct format

I'm trying to create a login aspx page.
What am I doing wrong here?
MySqlConnection cn = new MySqlConnection("Server=localhost;Database=securitytest; User=root;Password=sx;");
cn.Open();
MySqlCommand cmd = new MySqlCommand("Select * from login where username=#username and password=#password", cn);
//Add parameters to get the username and password
cmd.Parameters.Add("#username", OdbcType.VarChar);
cmd.Parameters["#username"].Value = this.Login1.UserName;
cmd.Parameters.Add("#password", OdbcType.VarChar);
cmd.Parameters["#password"].Value = this.Login1.Password;
MySqlDataReader dr = default(MySqlDataReader);
// Initialise a reader to read the rows from the login table.
// If row exists, the login is successful
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
e.Authenticated = true;
// Event Authenticate is true
}
The MySql database provider uses ? to locate parameters in SQL. So, use ? instead of # to mark your parameters in your SQL query:
MySqlCommand cmd = new MySqlCommand("Select * from login where username=?username and password=?password", cn);
cmd.Parameters.Add("?username", OdbcType.VarChar);
cmd.Parameters["?username"].Value = this.Login1.UserName;
...
Hope, this helps.

Categories