how to check the username exist in database or not - c#

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

Related

How to use multiple client side validation for both email and contact (same TextBox ) in asp.net c#?

how to use one TextBox and multiple validations i tried this
private Boolean checkemail() // for checking email in database
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);//sql connection string
Boolean emailavailable = false;
String myquery = "Select * from [test].[dbo].[MYFORM] where email='"+ TXTEmail.Text+"'";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = myquery;
cmd.Connection = conn;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet(); //dataset
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
emailavailable = true;
}
conn.Close();
return emailavailable;
}
c# code for the email check in database
First point: let's get back to the basics: js validation
Server side validation is performed by a web server, after input has been sent to the server.
Client side validation is performed by a web browser, before input is sent to a web server.
For example: Client side validation would include email formating (is it a valid email?) and checks like empty fields that the server needs etc.
Server side validation would check that the email is not yet used in another form by another user (like your case here) and it occurs in your backend system.
Second point: SqlInjection. As mentioned in the comments, use parameters for sql sanitization. It's a pretty basic exploit.
private Boolean checkemail() // for checking email in database
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);//sql connection string
Boolean emailavailable = false;
String myquery = "Select * from [test].[dbo].[MYFORM] where email = #email";
SqlCommand cmd = new SqlCommand();
cmd.Parameters.Add("#email", SqlDbType.Text);
cmd.Parameters["#email"].Value = TXTEmail.Text;
cmd.CommandText = myquery;
cmd.Connection = conn;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet(); //dataset
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
emailavailable = true;
}
conn.Close();
return emailavailable;
}
Third point: Multiple checks
If I understand what you are saying, you want to query with two parameters. Use the sql or operator like this:
String myquery = "Select * from [test].[dbo].[MYFORM] where email = #email or contact = #contact";
cmd.Parameters.Add("#email", SqlDbType.Text);
cmd.Parameters["#email"].Value = TXTEmail.Text;
cmd.Parameters.Add("#contact ", SqlDbType.Text);
cmd.Parameters["#contact "].Value = TXTEmail.Text;

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 validate Password and Username for website in 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
}
}
}
}

Assign SQL query result to session variable

I am trying to run a SQL query based on who's logged in which gets the Team_ID and assigns it to the session variable. I am having trouble assigning the result to the variable.
protected void ButtonLogin_Click(object sender, EventArgs e)
{
//check what user category was selected and login to appropriate page
if (DropDownListUserType.SelectedIndex == 1)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Web_FussConnectionString"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select * from Team_User where Email = #username and Password_1 = #password", con);
cmd.Parameters.AddWithValue("#username", UserName.Text);
cmd.Parameters.AddWithValue("#password", Password.Text);
SqlCommand cmdID = new SqlCommand("select Team_ID from Team_User where Email = #username and Password_1 = #password", con);
cmdID.Parameters.AddWithValue("#username", UserName.Text);
cmdID.Parameters.AddWithValue("#password", Password.Text);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
SqlDataReader reader = cmdID.ExecuteReader();
int Team_ID = reader.GetInt32(1);
Session["Team_ID"] = Team_ID;
Response.Redirect("AddPlayer.aspx");
}
else
{
ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Invalid Username and Password')</script>");
}
}
}
Your code doesn't make a whole lot of sense....
If you only want the Team_ID - why are you loading the whole row first, and then call the database again to get just the Team_ID???
I tried to simplify your code a good bit:
protected void ButtonLogin_Click(object sender, EventArgs e)
{
// check what user category was selected and login to appropriate page
if (DropDownListUserType.SelectedIndex == 1)
{
// define connection string and SQL query as strings
string connectionString = ConfigurationManager.ConnectionStrings["Web_FussConnectionString"].ConnectionString;
string query = "SELECT Team_ID FROM dbo.Team_User WHERE Email = #username AND Password_1 = #password";
// set up SqlConnection and SqlCommand in "using" blocks
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(query, con))
{
// define and fill parameters - DO NOT use .AddWithValue!
cmd.Parameters.Add("#username", SqlDbType.VarChar, 100).Value = UserName.Text;
cmd.Parameters.Add("#password", SqlDbType.VarChar, 100).Value = Password.Text;
// open connection, execute scalar, close connection
con.Open();
object result = cmd.ExecuteScalar();
// if we got back a result ....
if(result != null)
{
int teamID = Convert.ToInt32(result.ToString());
Session["Team_ID"] = teamID;
Response.Redirect("AddPlayer.aspx");
}
else
{
// if result is NULL, then the username+password
// were NOT found - do what needs to be done in that case here
}
}
}
}

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