views:

309

answers:

3

Hello all, I have problem with Login page.If i dont enter the Username or password it should say that"please enter a Username or password" instead its going to destination page i mean without entering anything in Login field if i hit submit button its going to welcome page actually which should not happen.

Here is my code please somebody tell me where is my mistake:

public class Login
{
  public string str = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString.ToString();
    public int GetLogin(string UserName, string Password)
    {
      SqlConnection con = new SqlConnection(str);
      SqlDataAdapter da = new SqlDataAdapter("select * from Login where UserName='"+UserName+"' and Password='"+Password+"'",con);
 DataSet ds = new DataSet();
        da.Fill(ds);
        if (ds.Tables[0].Rows.Count > 0)
        {
            if ((ds.Tables[0].Rows[0].ItemArray[0].ToString() == UserName) && (ds.Tables[0].Rows[0].ItemArray[1].ToString() == Password))
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }

        else
        {
            return -1;
        }
    }
Login.aspx.cs:
protected void BtnLogin_Click(object sender, EventArgs e)
    {
        Session["UserName"] = TxtUserName.Text;      

        Login lg = new Login();    

        if ((lg.GetLogin(TxtUserName.Text, TxtPassword.Text) == 1))
        {
            Response.Redirect("c1.aspx");

        }

        else if((TxtUserName.Text=="")&&(TxtPassword.Text==""))
        {
            Lbl1.Text = "Please Enter the UserName and Password";
        }

        else
        {

            Lbl1.Text = "Sorry,Invalid UserName or Password";
        }             

    }
+5  A: 

All of this functionality is already built in to ASP.NET.

Check out RequiredFieldValidator to validate your fields, or use Login Controls to handle all the form functionality for you.

Check out FormsAuthentication and Membership for user authentication.

Daniel Schaffer
+4  A: 

I don't really know what the problem is, because it looks like it should work, but you have a huge SQL injection issue. Test this out on a test database but enter this for your UserName.

' and 1 = 1; drop table Login; --

May I suggest you look up SqlParameter and do a search for "SqlParameter SQL Injection Attack"

Nick Berardi
+1  A: 

1.- the user and pass empty validations are after the db call so if you have a blank user with a blank password the login will succedd

2.- you are creating the sql query this is open to sql injection, please use parametrized queries.

Oscar Cabrero
Thanks Mr.Cabrero your No.1 suggestion is right and its working fine now......
Yet it's the No.2 that's the real problem. *frowns worriedly*
Iain M Norman