Solved

Check Password against database

Posted on 2010-09-02
17
595 Views
Last Modified: 2013-11-27
I am trying to create a log in for a page. My goal is to have  the user hit’s the submit then  the information entered  on the username and password textboxes are checked against the table “Account_Info” with the collum names Email and Password. Now here comes the tricky part. If the username does not exist the Username and Password are saved to the database and the panel dissipates. If the Username is correct but the password is wrong it propts you to enter the correct password. AND if the user is new and new information is saved then the panel dissipates.

here is my code so far...
protected void btnSubmitUserInfo_Click(object sender, EventArgs e)
    {

        if (textBox1.Text.Trim().Length <= 0) 
        {
            Label1.Visible = true;
            Label1.Text = "Please enter User Name.";
           // MessageBox.Show("Please enter User Name and Password.", "Message", MessageBoxButtons.OK);
        }
        else if (textBox2.Text.Trim().Length <= 0)
        {
            Label1.Visible = true;
            Label1.Text = "Please enter Password.";
        }

        System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection();
        con.ConnectionString = ConfigurationManager.ConnectionStrings["strDBCourseStandard"].ConnectionString;
        con.Open();
        string slelectString = "Select Email, Password from Account_Info where Email = '" + textBox1.Text + "' and Password = '" + textBox2.Text + "'";
        SqlCommand cmd = new SqlCommand();
        String strResult = String.Empty;
        strResult = (String)cmd.ExecuteScalar();
        con.Close();

        if (strResult.Length > 0)
        {
            System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection();
            con.ConnectionString = ConfigurationManager.ConnectionStrings["strDBCourseStandard"].ConnectionString;
            con.Open();
            SqlCommand cmdinsert = new SqlCommand();
            cmdinsert.CommandText = "update Account_Info set Email =" + textBox1.Text + " 
            string strInsert = "Insert into Account_Info (Email, Password) Values ("textBox1.Text +"," + textBox2.Text);
            


        }


        

    }

Open in new window

0
Comment
Question by:HawaiiDragon
  • 6
  • 5
  • 3
  • +2
17 Comments
 
LVL 8

Expert Comment

by:Gururaj Badam
ID: 33586236
What are you looking for?
0
 

Author Comment

by:HawaiiDragon
ID: 33586274
How to insert in to the database and also check the database to see if it exists.
0
 
LVL 8

Expert Comment

by:Gururaj Badam
ID: 33586314
you can use ExecuteNonQuery on the SQLCommand to persist

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery.aspx

and subsequently use the ExecuteReader to verify it's been persisted?
0
 
LVL 10

Expert Comment

by:Jini Jose
ID: 33586348
you can do like below..

select count(*) from account_info where email=your email and password=your password.
take the count

if the count =0 then you can display the error message as user name or password not matching etc...

if the count=1 then it is successfull login.
so you can save the log and continue.
0
 

Author Comment

by:HawaiiDragon
ID: 33586363
not enough detail..... would it be?

System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection();
            con.ConnectionString = ConfigurationManager.ConnectionStrings["strDBCourseStandard"].ConnectionString;
            con.Open();
            SqlCommand cmdinsert = new SqlCommand();
            cmdinsert.CommandText = "Insert into Account_Info (Email, Password) Values ("textBox1.Text +"," + textBox2.Text);
            cmdinsert.ExecuteNonQuery();
0
 
LVL 8

Expert Comment

by:Gururaj Badam
ID: 33586416
yes correct, that's for persisting.

using(SQLConnection conn = new SQLConnection(connString))
{
SQLCommand cmd = new SQLCommand(conn);
cmd.CommandText = "Select count(*) from Acount_Info where [Email] = <Value> AND [Password] = <value>"

SqlDataReader myReader = cmd.ExecuteReader();

while(myReader.Read())
   {
      // Verify if it's here and data is correct
   }
   myReader.Close();
}
0
 
LVL 20

Expert Comment

by:Marten Rune
ID: 33586492
Please don't store passwords in plain text. Hash them (with or without a salt, a salt is better ofcourse). Then use a hash function to compare passwords. This is how its done in a professional way.

Regards Marten
0
 
LVL 8

Expert Comment

by:Gururaj Badam
ID: 33586523
That's true. You should never store plain passwds. Encode/Encrypt them properly. And for verification you will have Encode/Encrypt the passwd and compare against that of DB.
0
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
LVL 7

Expert Comment

by:jdavistx
ID: 33586596
You also shouldn't allow user input to be used directly in a query.  Instead do something like:


SqlCommand cmd = new SqlCommand("SELECT Email, Password FROM Account_Info WHERE Email = @Email and Password = @password")
cmd.Parameters.Add("@email", SqlDbType.VarChar).Value = textBox1.Text;
cmd.Parameters.Add("@password", SqlDbType.VarChar).Value = textBox2.Text;

Open in new window

0
 

Author Comment

by:HawaiiDragon
ID: 33586743
getting error on ExecuteScalar(); (It states that the connection has not been established... but it has on the third line)......

System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection();
        con.ConnectionString = ConfigurationManager.ConnectionStrings["strDBCourseStandard"].ConnectionString;
        con.Open();
        SqlCommand cmd = new SqlCommand("SELECT Email, Password FROM Account_Info WHERE Email = @Email and Password = @password");
        cmd.Parameters.Add("@email", SqlDbType.Char).Value = textBox1.Text;
        cmd.Parameters.Add("@password", SqlDbType.Char).Value = textBox2.Text;
        cmd.ExecuteScalar();
        con.Close();
0
 
LVL 7

Expert Comment

by:jdavistx
ID: 33589911

try
{
	using(var con = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["strDBCourseStandard"].ConnectionString))
	{
		con.Open();
		SqlCommand cmd = new SqlCommand("SELECT Email, Password FROM Account_Info WHERE Email = @Email and Password = @password", con);
		cmd.Parameters.Add("@email", SqlDbType.Char).Value = textBox1.Text;
		cmd.Parameters.Add("@password", SqlDbType.Char).Value = textBox2.Text;
		cmd.ExecuteScalar();
		con.Close();
	}
}
catch(Exception e)
{
	//...
}

Open in new window

0
 
LVL 7

Expert Comment

by:jdavistx
ID: 33589949
Er, rather, the con.Close() is no longer needed within the using statement as well.
0
 
LVL 7

Accepted Solution

by:
jdavistx earned 500 total points
ID: 33589969
Sorry for the multiple posts. I should've taken a little more time before initially posting.
SqlConnection con = new SqlConnection();
try
{
	using(var con = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["strDBCourseStandard"].ConnectionString))
	{
		con.Open();
		SqlCommand cmd = new SqlCommand("SELECT Email, Password FROM Account_Info WHERE Email = @Email and Password = @password", con);
		cmd.Parameters.Add("@email", SqlDbType.Char).Value = textBox1.Text;
		cmd.Parameters.Add("@password", SqlDbType.Char).Value = textBox2.Text;
		cmd.ExecuteScalar();
	}
}
catch(Exception e)
{
	//...
}
finally
{
	con.Close();
}

Open in new window

0
 
LVL 8

Expert Comment

by:Gururaj Badam
ID: 33589990
finally block will throw a compile error as con is limited to using block. isn't it
0
 
LVL 7

Expert Comment

by:jdavistx
ID: 33590482
No, it's been initialized outside of the try block.
0
 
LVL 7

Expert Comment

by:jdavistx
ID: 33590573
Ah, but you'd need to remove the "var" before con in the using statement. I'm apparently awesome at typos!
0
 
LVL 20

Expert Comment

by:Marten Rune
ID: 33590834
the sql portion i e 'SqlCommand cmd = new SqlCommand("SELECT Email, Password ...' ought to go against a stored proc imho.

It enhances security, speeds up the database and is considered good practice.

create a proc, that accepts username and pwd. let it do the logic in adding or verifying the user and check responce from the stored proc.

the security enhancement lies in ONLY granting execute to the proc. the underlying tables is not directly accesible for the iis worker process account. this redimes any attempt to sql inject, and also controls the damnage of a compromised application/iis server.

These simple guidelines makes a vast impact on security for your application.

//Marten
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
In this article we will get to know that how can we recover deleted data if it happens accidently. We really can recover deleted rows if we know the time when data is deleted by using the transaction log.
Along with being a a promotional video for my three-day Annielytics Dashboard Seminor, this Micro Tutorial is an intro to Google Analytics API data.
This is used to tweak the memory usage for your computer, it is used for servers more so than workstations but just be careful editing registry settings as it may cause irreversible results. I hold no responsibility for anything you do to the regist…

867 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now