Linq To Sql Authenticate Login Credentials
I have a localdb in a WPF application and a table for storing a student's credentials, I want to compare the credentials entered by the user to the data in the Student table to see
Solution 1:
You are filling password with the PasswordChar, that seems kind of strange:
char password = tbxPassword.PasswordChar;
You should create a string called password instead of a char and fill it with tbxPassword.Text. I woud recommend you to at least insert a hashed password in the database and compare the hash from user input, to the hash in the database. Saving passwords in plaintext is a bad idea.
Use following method, for inserting a password in the database:
publicstaticstringCreatePasswordHash(string plainpassword)
{
byte[] data = System.Text.Encoding.ASCII.GetBytes(plainpassword);
data = new System.Security.Cryptography.SHA256Managed().ComputeHash(data);
return System.Text.Encoding.ASCII.GetString(data);
}
Following method can be used, to compare the password from user input, with hashed password in database:
publicstaticboolIsValidLogin(string id, string password)
{
password = CreatePasswordHash(password);
using(db = new DataClasses1DataContext())
{
Student student = (from u in db.Students
where u.Id.Equals(id) &&
u.Password.Equals(password)
select u);
if(student != null)
{
returntrue;
}
returnfalse;
}
}
The code at btnSubmit_Click event will be like:
privatevoidbtnSubmit_Click(object sender, RoutedEventArgs e)
{
string id = tbxUsername.Text;
string password = tbxPassword.Text;
if(IsValidLogin(id, password))
{
MessageBox.Show("Login Successful!");
}
else
{
MessageBox.Show("Login unsuccessful, no such user!");
}
}
Post a Comment for "Linq To Sql Authenticate Login Credentials"