Using stored procedure to login Asp.net - asp.net

I'm using asp.net to create a login page; in debugging I see the correct inputted data but I keep gettting the error message Invalid Username or Password even when it is valid. I have also executed the stored procedure with values and shows the correct result. I'm not sure what is happening.
protected void login_Click(object sender, EventArgs e)
{
String username = txtUserName.Text.ToString();
String password = txtPassword.Text;
string con = ConfigurationManager.ConnectionStrings["LoginConnectionString"].ToString();
SqlConnection connection = new SqlConnection(con);
connection.Open();
string passwords = encryption(password);
SqlCommand cmd1 = new SqlCommand("spLogin", connection);
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.AddWithValue("#UserName", username);
cmd1.Parameters.AddWithValue("#password", passwords);
SqlDataReader sqldr = cmd1.ExecuteReader();
if (sqldr.Read())
{
Session["UserName"] = username.ToUpper();
Response.Redirect("~/Home/Welcome.aspx");
}
else
{
lblError.Text = "Invalid Username or Password";
}
connection.Close();
sqldr.Close();
}
StoredProcedure
select * from Users u where UserName=#UserName and password=#password

Related

command failing in login code in C# on ASP.NET

I am making a website using ASP.NET framework.
My code for login page is as below, it is very simple since I'm trying to see step by step where it is going wrong. The C# code is:
protected void userLogin(object sender, EventArgs e)
{
string encoded_pass = encrypt_pass(Password.Text);
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Khulna_website"].ConnectionString);
connection.Open();
using (SqlCommand cmd = new SqlCommand ("Select * from users where user_email= #email and user_password = #password"))
{
cmd.Parameters.AddWithValue("#email", Email.Text);
cmd.Parameters.AddWithValue("#password", encoded_pass);
try
{
cmd.ExecuteNonQuery();
//SqlDataAdapter da = new SqlDataAdapter(cmd);
//DataTable dt = new DataTable();
//da.Fill(dt);
////Session["User"] = dt.Rows[0]["user_email"];
//Session["User_name"] = dt.Rows[0]["user_f_name"];
//loginlabel.Text = "Welcome, " + Session["User_name"];
}
catch
{
loginlabel.Text = "login error";
}
}
connection.Close();
}
Now every time I enter an email and password it always gives "login errorr".. Why the command is not executed?
Looks like you have declared the connection but haven't assigned it to the SqlCommand
using (SqlCommand cmd = new SqlCommand ("Select * from users where user_email= #email and user_password = #password",connection))
{
cmd.Parameters.AddWithValue("#email", Email.Text);
cmd.Parameters.AddWithValue("#password", encoded_pass);
Note i added the connection variable in the cmd declaration.
In future you may also like catching your errors in development:
catch (Exception ex)
{
loginlabel.Text = "login error: "+ ex.Message;
}
This will help you know what is going wrong.

change/forgot password with a hashed password possible?

i have implemented my user passwords to be hashed. And what i want is to implement a forgot/change password. However i am not able to convert the hashed password to the original password and that gives me a failure to do the forgot/change password feature. Here is my code from my registration page:
cmd.Parameters.AddWithValue("#Password", BusinessLayer.ShoppingCart.CreateSHAHash (txtPW.Text));
Here is my creathash code:
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 my changepassword page:
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 (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, 500));
com.Parameters["#Password"].Value = (txt_npassword.Text);
com.ExecuteNonQuery();
con.Close();
lbl_msg.Text = "Password changed Successfully";
}
else
{
lbl_msg.Text = "Please enter correct Current password";
}
}
What i want to do is to be able to convert my hashed password to the original password for it to be changed. Any tricks? or is it possible though?

how to auto login after registration in asp.net

I want to login automatically after registration by using a session like Session["ud"] , but I don't know where should I put it.
public partial class index : System.Web.UI.Page
{
SqlConnection cnn = new SqlConnection(ConfigurationManager.AppSettings["dbpath"]);
protected void btnSave_Click(object sender, EventArgs e)
{
long idx;
SqlCommand cmd = new SqlCommand();
cmd.Connection = cnn;
cmd.CommandText = "Insert into tblUser (UInfo,UEmail,UName,UPass, UGender) Values (#P1,#P2,#P3,#P4,#P5) select ##Identity";
cmd.Parameters.AddWithValue("#P1", txtInfo.Text);
cmd.Parameters.AddWithValue("#P2", txtEmail.Text);
cmd.Parameters.AddWithValue("#P3", txtUserName.Text);
cmd.Parameters.AddWithValue("#P4", txtPass.Text);
cmd.Parameters.AddWithValue("#P5", rdbMale.Checked);
cnn.Open();
idx = Convert.ToInt64(cmd.ExecuteScalar()); // i think here we can do something
cnn.Close();
here we want to upload the image of user and it works correctly
string fn = "";
if (FileUpload1.HasFile == true)
{
fn = FileUpload1.FileName;
string des = Server.MapPath("\\UserImg\\") + idx.ToString() + ".jpg";
FileUpload1.PostedFile.SaveAs(des);
SqlCommand cmdUpdate = new SqlCommand();
cmdUpdate.Connection = cnn;
cmdUpdate.CommandText = "Update tblUser Set UImg=#P5 where UId=#P0";
cmdUpdate.Parameters.AddWithValue("#P5", idx.ToString() + ".jpg");
cmdUpdate.Parameters.AddWithValue("#P0", idx);
cnn.Open();
cmdUpdate.ExecuteNonQuery();
cnn.Close();
}
Response.Redirect("Profile.aspx");
}
}
once you have entered data into in sql database you will get id of new user here
idx = Convert.ToInt64(cmd.ExecuteScalar()); // i think here we can do something
Once you get the id assign it to your session
idx = Convert.ToInt64(cmd.ExecuteScalar()); // i think here we can do something
cnn.Close();
Session["ud"]=idx;
once you have assigned session ,you just have to redirect to required page and validate Session variable if it's null or not.
i hope on Profile.aspx page you are checking for same session variable.
Profile.aspx.cs--on page load
if (Session["ud"] != null)
{
//successfull login
}
else
{
//redirect to login page
}

Data Reader and Invalid attempt to read when no data is present

This is my code:
protected void logujButton_Click(object sender, EventArgs e)
{
string user = "data source=myHostServer; database = myDataBase; user id=myLogin; password=myPassword";
SqlConnection con2 = new SqlConnection(user);
con2.Open();
string loguj = "select count(*) from uzytkownik where Login = '"+ logujTextBox.Text +"'";
SqlCommand command = new SqlCommand(loguj, con2);
int wartosc = Convert.ToInt32(command.ExecuteScalar().ToString());
con2.Close();
if (wartosc == 1)
{
con2.Open();
SqlCommand pobierzHaslo = new SqlCommand("select Haslo from uzytkownik where Login = '" + logujTextBox.Text + "'", con2);
SqlDataReader rdr = pobierzHaslo.ExecuteReader();
string haslo = rdr["Haslo"].ToString();
if (haslo == hasloTextBox.Text)
{
errorLabel.Text = "Prawidlowe Haslo !";
}
else
{
errorLabel.Text = "Zle haslo !";
}
}
else
{
errorLabel.Text = "Taki uzytkownik nie istnieje !";
}
}
When I press button, this error is appearing: "Invalid attempt to read when no data is present". Could You tell me, where i made mistake ?. Thanks for advise !
You haven't read anything from the reader yet. You have to call the Read() method:
SqlDataReader rdr = pobierzHaslo.ExecuteReader();
if (rdr.Read())
{
string haslo = rdr["Haslo"].ToString();
....
}
If you have access to SSMS, run the query directly in a query window and make sure that you get data back. Your query may be bad. It is most likely an error from the ExecuteReader method of your SqlDataReader, based on the text of the error message.

asp.net login web page using sql server

i am stuck in my login page..my button click event is as follows:
protected void Button1_Click(object sender, EventArgs e)
{
string cs = "Data Source=ims-aab46237892;Initial Catalog=Inventory;Integrated Security=True";
string SelectString = "SELECT COUNT(*) FROM user WHERE username = #Username AND password = #Password";
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand(SelectString,con);
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = SelectString;
SqlParameter username = new SqlParameter("#Username",SqlDbType.VarChar,50);
username.Value = TextName.Text.Trim().ToString();
cmd.Parameters.Add(username);
SqlParameter password = new SqlParameter("#Password", SqlDbType.VarChar, 50);
password.Value = TextPass.Text.Trim().ToString();
cmd.Parameters.Add(password);
con.Open();
if(cmd.ExecuteScalar() != null)
Response.Redirect("Home.aspx");
else
Response.Redirect("wrongpasspage.aspx");
con.Close();
}
and my data table has the required username and password fields.. error i am getting is incorrect syntax near keyword user... plz help
user is a reserved keyword in SQL server. Try [user] or rename your table to Users.
use [user] instead of user in SelectString statement.

Resources