Как избежать входа в систему с пустым паролем в ASP.NET MVC 5?
Я работаю над проектом ASP.NET MVC 5, где я создал настроенную страницу входа и регистрации. Приложение работает нормально, но проблема в том, что я могу войти, даже когда мое поле пароля пусто.
Вот код для контроллера (я использовал все пространства имен и ссылки правильно)
public class UserController : Controller
{
//
// GET: /Register/
public ActionResult Index()
{
return View();
}
[HttpGet]
public ActionResult LogIn()
{
return View();
}
[HttpPost]
public ActionResult LogIn(Models.Register userr)
{
if (IsValid(userr.Email_Id, userr.Password))
{
FormsAuthentication.SetAuthCookie(userr.Email_Id, false);
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", "Login details are wrong.");
}
return View(userr);
}
[HttpGet]
public ActionResult Register()
{
return View();
}
[HttpPost]
public ActionResult Register(Models.Register user)
{
try
{
if (ModelState.IsValid)
{
using (var db = new MvcApplication2.Models.OnlineEducationEntities())
{
var newUser = db.Registers.Create();
newUser.Email_Id = user.Email_Id;
newUser.Password = user.Password;
newUser.Student_Name = user.Student_Name;
newUser.DOB= DateTime.Now;
db.Registers.Add(newUser);
db.SaveChanges();
return RedirectToAction("LogIn", "User");
}
}
else
{
ModelState.AddModelError("", "Data is not correct");
}
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
foreach (var ve in eve.ValidationErrors)
{
Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
}
}
throw;
}
return View();
}
public ActionResult LogOut()
{
FormsAuthentication.SignOut();
return RedirectToAction("LogIn", "User");
}
private bool IsValid(string email, string password)
{
var crypto = new SimpleCrypto.PBKDF2();
bool IsValid = false;
using (var db = new MvcApplication2.Models.OnlineEducationEntities())
{
var user = db.Registers.FirstOrDefault(u => u.Email_Id == email);
if (user != null)
{
if (user.Password == crypto.Compute(password, user.Password))
{
IsValid = true;
}
}
}
return IsValid;
}
}
И это мой взгляд:
@model MvcApplication2.Models.Register
@{
ViewBag.Title = "LogIn";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>LogIn</h2>
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>Register</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Email_Id)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Email_Id)
@Html.ValidationMessageFor(model => model.Email_Id)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Password)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Password)
@Html.ValidationMessageFor(model => model.Password)
</div>
<p>
<input type="submit" value="LogIn" />
</p>
</fieldset>
}
< div>
@Html.ActionLink("Register Now", "Register")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
1 ответ
Решение
Добавьте этот чек к вашему IsValid
метод:
private bool IsValid(string email, string password)
{
if (string.IsNullOrWhiteSpace(password) || password.Length < 6)
return false;
//... etc.
Проблема в том, что вы не используете ModelState.IsValid
Вам понадобится альтернатива. Ваш IsValid
метод, кажется, что альтернатива.