Monday, July 27, 2009

How to validate this in C# ?

I have develped a system using C# and ASP.Net.and I have used password and a user


name to login to the system.But always a user mistakenly insert a ' mark in user name field the program shows a error saing that An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code





Additional information: Unclosed quotation mark before the character string 'jhone''.


Line 1: Incorrect syntax near 'jhone''.


How should I validate this username?

How to validate this in C# ?
Your code is vulnerable to SQL Injections.





When Querying data in your DataTier use parameters with your command objects instead of constructing the text of your query at runtime.





This is the pattern you should follow:


//read username / password from form


string Username = txtUsername.Text;


string Password = txtPassword.Text;





SqlCommand cmd = new SqlCommand (" SELECT COUNT(*) FROM [Users] WHERE UserName = @Username AND [Password] = @Password ") ;





// add parameters - parameters protect you from injections


//


cmd.CommandType = CommandType . Text;


cmd.Parameters. AddWithValue("@Username", Username);


cmd.Parameters. AddWithValue("@Password", Password);





// Read the scalar returned from your query


//


bool Authenticated = ( (int)cmd.ExecuteScalar() %26gt; 0 );








Hope this helps.
Reply:You need to Include


"System.Text.RegularExpressions" namespace to your code





Then do something like below





if (Regex.Match(username, "[^a-zA-Z0-9_]").Success || Regex.Match(password, "[^a-zA-Z0-9_]").Success)


{


//Go back to login page and give user error message


}
Reply:You should always use a stored procedure to validate a login. You can pass the values as parameters and the special characters will not harm the stored procedure. You can also remove all "--" and substitute all single quotes with two single quotes.





RJ
Reply:we get the strng jhone as an array,a[100]


if a[1]==''';


{


for(a=1;a%26lt;i;a++)


{


a[i]=a[i+1];


}


}
Reply:at the client level...you can have a regular expression validator to validate the textbox for the email...


and have the regular expression for email which is available in the regular expression validator....





or at the server side... u can alter your queries to to escape the single quote... say the variable for your email is em





use em.Replace(" ' "," '' ");





here you are replacing a single quote with two single quotes.


this will escape the single quote in the query...





(note that it is 2 single quotes and not a double quote you are replacing the single quote with...)


No comments:

Post a Comment