2016-12-30 63 views
2

這是SQL注入證明嗎?或者至少可以嗎?我在網上得到這個,所以我真的可以使用一些幫助。我目前正在構建一個非常大的程序,如果我想讓它付費,我決定添加一個登錄頁面。請幫忙!是我的代碼SQL注入證明?

if (txt_UserName.Text == "" || txt_Password.Text == "") 
{ 
    MessageBox.Show("Please provide a Username and Password"); 
    return; 
} 

try 
{ 
    // Create SqlConnection 
    SqlConnection con = new SqlConnection(cs); 

    SqlCommand cmd = new SqlCommand("Select * from tbl_Login where UserName = @username and Password = @password", con); 

    cmd.Parameters.AddWithValue("@username", txt_UserName.Text); 
    cmd.Parameters.AddWithValue("@password", txt_Password.Text); 

    con.Open(); 

    SqlDataAdapter adapt = new SqlDataAdapter(cmd); 
    DataSet ds = new DataSet(); 
    adapt.Fill(ds); 

    con.Close(); 

    int count = ds.Tables[0].Rows.Count; 

    // If count is equal to 1, than show frmMain form 
    if (count == 1) 
+0

不是。您應該使用準備好的語句。在SqlConnector文檔中閱讀它。我正在使用手機,所以現在無法發佈完整答案。 – SplittyDev

+1

@SplittyDev與此相比,準備好的聲明如何提供任何保護?這是一樣的,但準備,在這種情況下,甚至可能沒有用。 –

+0

注意:使用DataSet進行這種查詢非常糟糕。他們速度慢,內存不足,你會更好地使用'DataReader' –

回答

3

您的代碼是SQL注入證明。對於普通SQL查詢,我個人喜歡用Dapper ORM這是在StackOverflow上使用。

它基本上是相同的,但少了很多代碼,並返回強類型的值,而不是數據集。

例如,

public class User 
{ 
    public string UserName { get; set; } 
    public string Password { get; set; } 
} 

User user; 
using (IDbConnection cnn = new SqlConnection(cs)) 
{ 
    user = cnn.Query<User>(
     "Select UserName, Password from tbl_Login where [email protected] and [email protected]", 
     new { username = txt_UserName.Text, password = txt_Password.Text }) 
     .SingleOrDefault(); 
} 

if (user != null) 
{ 
    // Do someting 
} 

FYI:看來你存儲明文口令。如果是這樣,這不是一個好的做法。相反,你想存儲鹽漬散列密碼。

+0

它們被散列。我只是沒有包括那個代碼 – RockyBoa

+0

如果是這樣的話,那麼你已經準備好了,並且很好。 – Win