[英]Linq to SQL authenticate login credentials
我在WPF應用程序中有一個localdb,還有一個用於存儲學生憑據的表,我想將用戶輸入的憑據與Student表中的數據進行比較,以查看該學生是否存在。 這是我所擁有的,但並不完全正確。
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!");
}
}
}
}
您正在使用PasswordChar
填充password
,這似乎有點奇怪:
char password = tbxPassword.PasswordChar;
您應該創建一個名為password
而不是char的字符串,並用tbxPassword.Text
填充它。 我建議您至少在數據庫中插入一個哈希密碼,並將用戶輸入的哈希值與數據庫中的哈希值進行比較。 以明文形式保存密碼不是一個好主意。
使用以下方法在數據庫中插入密碼:
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);
}
可以使用以下方法將用戶輸入的密碼與數據庫中的哈希密碼進行比較:
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;
}
}
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.