我发现在盐类中使用散列密码比MD5/ that 256要好得多,所以我不使用PBKDF2对它们进行散列。但是,我想知道这是否是授权我的用户的正确方法。我也有记录授权的逻辑。当同一个IP输入了不正确的登录/通行证时,它将被禁用5分钟。
a正在传递Username和Password。Username。[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Authorize(Administrator a)
{
// Check if there are no failed login attempts in last 5 minutes
if (!this.CanAdminLogin)
{
TempData["loginTooManyAttempts"] = true;
return RedirectToAction("index", "home");
}
// If model is not validated return login view to show error messages (javascript disabled)
if (!TryValidateModel(a))
{
return View("Authorize", a);
}
// Check if username exists, if not then log and show that login failed
var admin = _db.Administrators.Where(x => x.Username == a.Username).SingleOrDefault();
if (admin == null || admin.Username != a.Username)
{
this.LogAuthorization(a, false);
TempData["loginFailed"] = true;
return RedirectToAction("index", "home");
}
// Username exists, check if passwords match
ICryptoService cryptoService = new PBKDF2();
string hash = cryptoService.Compute(a.Password, admin.PasswordSalt);
if (hash == admin.Password)
{
this.LogAuthorization(a, true);
Session["adminId"] = admin.ID;
}
else
{
this.LogAuthorization(a, false);
TempData["loginFailed"] = true;
}
// Login successfull
return RedirectToAction("index", "home");
}发布于 2015-04-16 16:34:45
我真的认为,您应该合并所有这些if语句,使它们成为if/elseif/else语句。只需将所有变量声明移到顶部即可。
然后就变成这个
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Authorize(Administrator a)
{
var admin = _db.Administrators.Where(x => x.Username == a.Username).SingleOrDefault();
ICryptoService cryptoService = new PBKDF2();
string hash = cryptoService.Compute(a.Password, admin.PasswordSalt);
if (!this.CanAdminLogin) // Check if there are no failed login attempts in last 5 minutes
{
TempData["loginTooManyAttempts"] = true;
return RedirectToAction("index", "home");
}
else if (!TryValidateModel(a)) // If model is not validated return login view to show error messages (javascript disabled)
{
return View("Authorize", a);
}
else if (admin == null || admin.Username != a.Username) // Check if username exists, if not then log and show that login failed
{
this.LogAuthorization(a, false);
TempData["loginFailed"] = true;
return RedirectToAction("index", "home");
}
else if (hash == admin.Password) // Username exists, check if passwords match
{
this.LogAuthorization(a, true);
Session["adminId"] = admin.ID;
}
else
{
this.LogAuthorization(a, false);
TempData["loginFailed"] = true;
}
// Login successfull
return RedirectToAction("index", "home");
}我还将评论移至它们所附加的行的末尾。请记住,其中一些评论是根本不需要的。
这里需要的评论
// Check if there are no failed login attempts in last 5 minutes这是必需的,因为否则我就不知道为什么Admin无法登录,也不知道有一个实例会更改此布尔值。
// If model is not validated return login view to show error messages (javascript disabled)我可以从代码中看出发生了什么,但我不知道(javascript disabled)与这段代码有什么关系?
https://codereview.stackexchange.com/questions/20507
复制相似问题