Solved

Check Password against database

Posted on 2010-09-02
17
597 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
What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

 
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
 
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

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Reading the Web.Config using IIS 7.5? 4 35
View SQL 2005 Job package 16 41
C# bracket error 3 30
Create a WebAPI using a generic return parameter 9 24
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Microsoft Active Directory, the widely used IT infrastructure, is known for its high risk of credential theft. The best way to test your Active Directory’s vulnerabilities to pass-the-ticket, pass-the-hash, privilege escalation, and malware attacks …
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.

805 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