I have hased my password right there on in the registration.aspx. having this code in my business layer:
public static string CreateSHAHash(string Phrase)
{
SHA512Managed HashTool = new SHA512Managed();
Byte[] PhraseAsByte = System.Text.Encoding.UTF8.GetBytes(string.Concat(Phrase));
Byte[] EncryptedBytes = HashTool.ComputeHash(PhraseAsByte);
HashTool.Clear();
return Convert.ToBase64String(EncryptedBytes);
}
and this code in the register page:
scm.Parameters.AddWithValue("#Password", BusinessLayer.ShoppingCart.CreateSHAHash(txtPW.Text));
Having the codes above, the password are being hashed in the DB and it is working fine when I log in with this code:
protected void btn_Login_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string checkuser = "select count(*) from UserData where Username = '" + txtUser.Text + "'";
SqlCommand scm = new SqlCommand(checkuser, conn);
int temp = Convert.ToInt32(scm.ExecuteScalar().ToString());
conn.Close();
if (temp == 1)
{
conn.Open();
string checkPassword = "select Password from UserData where Username ='" + txtUser.Text + "'";
SqlCommand passCom = new SqlCommand(checkPassword, conn);
string password = passCom.ExecuteScalar().ToString();
if (password == BusinessLayer.ShoppingCart.CreateSHAHash(txtPassword.Text))
{
Session["New"] = txtUser.Text;
Response.Write("<script>alert('Logged In')</script>");
Response.Redirect("OrderNow.aspx");
}
else
{
lblcrederror.Text = ("Credentials dont match");
}
}
else
{
lblcrederror.Text = ("Credentials dont match");
}
However when I change it having this code in my changepassword.aspx, its not letting me in with my new password.
protected void btn_update_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(conn);
con.Open();
str = "select * from UserData ";
com = new SqlCommand(str, con);
SqlDataReader reader = com.ExecuteReader();
while (reader.Read())
{
if (BusinessLayer.ShoppingCart.CreateSHAHash(txt_cpassword.Text) == reader["Password"].ToString())
{
up = 1;
}
}
reader.Close();
con.Close();
if (up == 1)
{
con.Open();
str = "update UserData set Password=#Password where UserName='" + Session["New"].ToString() + "'";
com = new SqlCommand(str, con);
com.Parameters.Add(new SqlParameter("#Password", SqlDbType.VarChar, 50));
com.Parameters["#Password"].Value = BusinessLayer.ShoppingCart.CreateSHAHash(txt_npassword.Text);
com.ExecuteNonQuery();
con.Close();
lbl_msg.Text = "Password changed Successfully";
}
else
{
lbl_msg.Text = "Please enter correct Current password";
}
}
What am I missing here?
Check if the 50 truncates the hash.
com.Parameters.Add(new SqlParameter("#Password", SqlDbType.VarChar, 50));
On a sidenote i see that your solution is very open to SQL injection.
"select Password from UserData where Username ='" + txtUser.Text + "'";
A user can write sql statements in the textbox, and hijack your database, create his own tables or drop the whole database. You should always parameterize the queries. I see that you did that to the Update statement, but you should consider doing it for all of your variables.
This quickly creates a lot of code, so i would also consider making an SQL wrapper, that wraps in all of the things you repeat. When you are done refactoring it could look something like this:
var sql = new SqlWrapper("select Password from UserData where Username = #username", txtUser.Text);
var dataSet = sql.Execute();
Then you can hide all of your connectionstring, commands++ behind this wrapper and only tell the wrapper what you actually care about.
You should also consider using a salt for your password. If you and I have the same password, the hash will be the same. A salt will fix this problem.
A good article about password security -> https://crackstation.net/hashing-security.htm
Related
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");
}
}
I am new to C#. I have Activation Data Type Bit in my database default value 0.
My question is how can I block user to login before activation email send
after registration is completed the activation is null in database but still user can login how can I fix this problem please help.
Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Loginbtn_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegisterConnectionString"].ConnectionString);
conn.Open();
string checkuser = "select count(*) from UserData where UserName='" + UserName.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 UserData where UserName='" + UserName.Text + "'";
SqlCommand passComm = new SqlCommand(checkPasswordQuery, conn);
string password = passComm.ExecuteScalar().ToString().Replace(" ", "");
if (password == Password.Text && UserName.Text == "Admin" )
{
Session["New"] = UserName.Text;
Response.Redirect("~/Admin/UserManager.aspx");
}
if (password == Password.Text)
{
Session["New"] = UserName.Text;
Response.Redirect("~/Account/UserPage.aspx");
}
else
{
invalidlbl.Text = "Please check your username and password";
}
}
}
Here is the image of my database:
You said activation is null in database. So, when user tried to login, fetch and check if the activation is still null in database and if so then just so a message to user saying activate your account first and redirect him/her to home page.
EDIT: per your comment, not going to give you full code but here is an example of what I am saying. BTW, consider using SQL Parameter to avoid SQL Injection attack.
string checkuser = "select count(*) from UserData where UserName=#uname and activation != null";
SqlCommand com = new SqlCommand(checkuser, conn);
com.Parameters.Add("#uname", SqlDbType.VarChar).Value = UserName.Text.Trim();
int temp = Convert.ToInt32(com.ExecuteScalar());
if(temp > 0)
{
// do processing
}
else
{
// not activated ... throw alert
}
SqlConnection con = new SqlConnection(#"Data Source=STRONGLION;Initial Catalog=GIP;Integrated Security=True");
private void btnLogin_Click(object sender, EventArgs e)
{
SqlDataAdapter sda = new SqlDataAdapter("Select count(*) from tblLogin where Gebruikersnaam = '" + txtGebruikersnaam.Text + "' and Paswoord = '" + txtPaswoord.Text + "' and Accounttype'" + "'", con);
DataTable dt = new DataTable();
sda.Fill(dt);
if (Accounttype == "1")
{
if (dt.Rows[0][0].ToString() == "1")
{
this.Hide();
FormAdmin ss = new FormAdmin();
ss.Show();
}
else
{
MessageBox.Show("Error");
}
}
else if (Accounttype == "0")
{
if (dt.Rows[0][0].ToString() == "1")
{
this.Hide();
FormWerknemer ss = new FormWerknemer();
ss.Show();
}
else
{
MessageBox.Show("Error");
}
}
}
I have a login form that reads data from a database. What I want is that I can open a form based on what type of user logs in. Above you see a general example how I want it to work.
For example in the database I have 3 things username, password and accounttype, if account type is 1 then its an admin type of account if its 0 then its just a normal account.
Hope someone can help out, thanks in advance!
Your query is wrong, the last part of your WHERE statement is meaningless
"' and Accounttype'" + "'", con);
where is the value for the field Accounttype?
However there is a bigger problem here and is the string concatenation to build your sql text. This could be used to create an Sql Injection attack or it could be simply a source of bugs if your input values cannot be correctly parsed.
You could use a parameterized query as this one
string cmdText = #"Select count(*)
from tblLogin
where Gebruikersnaam = #name and
Paswoord = #pwd and
Accounttype = #type";
and there is no need to build an SqlDataAdapter and a DataTable if you want to get a simple scalar value from your data (the count)
using(SqlConnection con = new SqlConnection(.....))
using(SqlCommand cmd = new SqlCommand(cmdText, con))
{
con.Open();
cmd.Parameters.Add("#name", SqlDbType.NVarChar).Value = txtGebruikersnaam.Text;
cmd.Parameters.Add("#pwd", SqlDbType.NVarChar).Value = txtPaswoord.Text;
cmd.Parameters.Add("#type", SqlDbType.NVarChar).Value = Accounttype;
int countType = Convert.ToInt32(cmd.ExecuteScalar());
if(countType == 0)
MessageBox.Show("No user found for the type requested");
else
{
if (Accounttype == "1")
{
this.Hide();
FormAdmin ss = new FormAdmin();
ss.Show();
}
else if (Accounttype == "0")
{
this.Hide();
FormWerknemer ss = new FormWerknemer();
ss.Show();
}
}
}
Consider also the advice given in the comments above. You should not store passwords in plain text inside the database. This is a big security risk because everyone that could look at your table could see the password of your users.
I'm trying to do a Login code in C# with MySQL. Basically the user enters a username and password then the code checks the database if the the password is correct. I'm having trouble getting the code to read from the data base... Here is where I'm at.
public string strUsername;
public string strPassword;
//Connect to DataBase
MySQLServer.Open();
//Check Login
MySqlDataReader mySQLReader = null;
MySqlCommand mySQLCommand = MySQLServer.CreateCommand();
mySQLCommand.CommandText = ("SELECT * FROM user_accounts WHERE username =" +strUsername);
mySQLReader = mySQLCommand.ExecuteReader();
while (mySQLReader.Read())
{
string TruePass = mySQLReader.GetString(1);
if (strPassword == TruePass)
{
blnCorrect = true;
//Get Player Data
}
}
MySQLServer.Close();
From what I've done in the past, I thought this would work but if I print it, it Seems like its not being read. I am still fairly new to MySQL so any help would be Great.
Non-numeric field value must be enclosed with single quote.
mySQLCommand.CommandText = "SELECT * FROM user_accounts WHERE username ='" +strUsername + "'";
mySQLCommand.Connection=MySQLServer;
but you have to use Parameters to prevent SQL Injection.
mySQLCommand.CommandText = "SELECT * FROM user_accounts WHERE username =#username";
mySQLCommand.Connection=MySQLServer;
mySQLCommand.Parameters.AddWithValue("#username",strUsername);
string con_string = #"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Database.mdf;Integrated Security=True;User Instance=True";
string query = "SELECT * FROM Users WHERE UseName='" + txtUserName.Text.ToString() + "' AND Password='" + txtPassword.Text + "'";
SqlConnection Con = new SqlConnection(con_string);
SqlCommand Com = new SqlCommand(query, Con);
Con.Open();
SqlDataReader Reader;
Reader = Com.ExecuteReader();
if (Reader.Read())
{
lblStatus.Text="Successfully Login";
}
else
{
lblStatus.Text="UserName or Password error";
}
Con.Close();
As AVD said you should use parameters to prevent sql injection....
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.