今天做了一个小的登录程序,要求是用户连续登录错误3次之后锁定该用户,过了一定的时间才能再次登录。于是乎在探讨的时候出现了以下的代码:
private void UpdateErrortime()
{
SqlConnection conn = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
conn.Open();
cmd.CommandText = "update T_User set [email protected] where [email protected]";
cmd.Parameters.AddWithValue("errortime",DateTime.Now);
cmd.Parameters.AddWithValue("@username",txtUserName.Text);
cmd.ExecuteNonQuery();
}
DateTime errortime = GetErrorTime();
//Subtract函数减去指定时间,返回一个时间差,这个返回值可以转换成我们需要的形式,比如可以转换层总共多少秒,或者总共是多少分。。。
TimeSpan span = DateTime.Now.Subtract(errortime);
double theseconds = span.TotalSeconds;
if (theseconds < 15)
{
MessageBox.Show("您已经连续3次输入错误的密码,已被系统锁定,请15秒之后再次重试,或者到服务窗口解锁");
//程序执行到此为止,后面代码不再执行
return;
}
else
{
errorcount = 0;
UpdateError(errorcount);
}
这段代码看似没有问题,但实际应用中会发现只需要修改本地的时间,就能绕过锁定登录的限制,而用以下代码则不会产生问题: int secondspan = GetErrorTime1();
//如果间隔时间小于解锁时间则返回程序
if (secondspan < 15)
{
MessageBox.Show("您已经连续3次输入错误的密码,已被系统锁定,请15秒之后再次重试,或者到服务窗口解锁");
//程序执行到此为止,后面代码不再执行
return;
}
private int GetErrorTime1()
{
SqlConnection conn = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
conn.Open();
cmd.CommandText = "select DATEDIFF([second],ErrorTime,getdate()) from T_User where [email protected]";
cmd.Parameters.AddWithValue("@username", txtUserName.Text);
//返回一行一列
object obj = cmd.ExecuteScalar();
return Convert.ToInt32(obj);
}
BUG总结: 用户锁定的时间是通过客户端时间验证的而不是服务器,通过完全调用服务器的时间来做判断,就能完美解决这一问题。