[英]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 if the student exists. 我在WPF应用程序中有一个localdb,还有一个用于存储学生凭据的表,我想将用户输入的凭据与Student表中的数据进行比较,以查看该学生是否存在。 Here is what I have but it isn't quite right.
这是我所拥有的,但并不完全正确。
private void btnSubmit_Click(object sender, RoutedEventArgs e)
{
string id = tbxUsername.Text;
char password = tbxPassword.PasswordChar;
using (DataClasses1DataContext db = new DataClasses1DataContext())
{
Student student = (from u in db.Students
where u.Id.Equals(id) &&
u.Password.Equals(password)
select u);
if(student != null)
{
MessageBox.Show("Login Successful!");
}
else
{
MessageBox.Show("Login unsuccessful, no such user!");
}
}
}
}
You are filling password
with the PasswordChar
, that seems kind of strange: 您正在使用
PasswordChar
填充password
,这似乎有点奇怪:
char password = tbxPassword.PasswordChar;
You should create a string called password
instead of a char and fill it with tbxPassword.Text
. 您应该创建一个名为
password
而不是char的字符串,并用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: 使用以下方法在数据库中插入密码:
public static string CreatePasswordHash(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: 可以使用以下方法将用户输入的密码与数据库中的哈希密码进行比较:
public static bool IsValidLogin(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)
{
return true;
}
return false;
}
}
The code at btnSubmit_Click event will be like: btnSubmit_Click事件中的代码将类似于:
private void btnSubmit_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!");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.