[英]Why Login control C# gives authentications to any username and a password
我正在创建一个登录表单,该表单对创建的数据库中的用户名和密码进行身份验证,代码运行时没有错误,但是在写入任何用户名或密码时,即使它不存在登录的数据库,我也需要它进行身份验证并仅使数据库用户名登录。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace WebApplication1
{
public partial class LoginTest : System.Web.UI.Page
{
private string strcon = WebConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
this.UnobtrusiveValidationMode = System.Web.UI.UnobtrusiveValidationMode.None;
}
private bool UserLogin(string un, string pw)
{
SqlConnection conn = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("Select id from student where id=@un and Password=@pw", conn);
cmd.Parameters.AddWithValue("@un", un);
cmd.Parameters.AddWithValue("@pw", pw);
conn.Open();
string result = Convert.ToString(cmd.ExecuteScalarAsync());
if (String.IsNullOrEmpty(result)) return false; return true;
}
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
string un = Login1.UserName;
string pw = Login1.Password;
bool result = UserLogin(un, pw);
if (result)
{
e.Authenticated = true;
Session["username"] = un;
}
else e.Authenticated = false;
}
}
}
cmd.ExecuteScalarAsync()
返回一个Task
对象。 将其转换为字符串将始终成功; 它将创建一个字符串“ System.Threading.Tasks.Task”,该字符串当然不能为空或为null。
您需要await
对ExecuteScalarAsync()
的调用,或者您需要调用ExecuteScalarAsync().Result
,该操作将阻塞直到查询操作完成。
此外 ,请确保您正在制作的任何应用程序-即使您认为这是一个玩具-都使用正确的单向哈希密码。 在Stackoverflow和其他地方,有很多关于如何安全存储密码的建议。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.