I work on web application asp.net mvc core .net 5
i can't modify action login
to accept 3 login attempt failed only .
if he try with wrong password or wrong email account after that then block it .
I using user identity login
what I try
[HttpPost]
public async Task<IActionResult> Login(LoginVM loginVM)
{
if (!ModelState.IsValid) return View(loginVM);
var user = await _userManager.FindByEmailAsync(loginVM.EmailAddress);
if(user != null)
{
var passwordCheck = await _userManager.CheckPasswordAsync(user, loginVM.Password);
if (passwordCheck)
{
var result = await _signInManager.PasswordSignInAsync(user, loginVM.Password, false, false);
if (result.Succeeded)
{
return RedirectToAction("Index", "Movies");
}
}
TempData["Error"] = "Wrong credentials. Please, try again!";
return View(loginVM);
}
TempData["Error"] = "Wrong credentials. Please, try again!";
return View(loginVM);
}
updated post can you help me by solution general working as session without using identity membership so i can use it on another login or another logic
CodePudding user response:
It seems you are trying with Identity ,You Could try as below :
var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: true);
If you set lockoutOnFailure: true,when someone login with wrong password ,the number of AccessFailedCount column would add 1
And you could set the MaxFailedAccessAttempts as below in startup:
services.AddDefaultIdentity<AppUser>(options =>
{
options.SignIn.RequireConfirmedAccount = true;
options.Lockout.MaxFailedAccessAttempts = 3;
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
})
Accroding to your Update:
[HttpPost]
public IActionResult Login(User user)
{
string failure;
HttpContext.Request.Cookies.TryGetValue("LoginInfo", out failure);
int fail = Convert.ToInt32(failure);
if (fail > 3)
{
//You could add ModelState here and retrun current Page ,it dependens on how your frontend designed
return View("Failure");
}
// your login attempts here
//var passwordCheck = await _userManager.CheckPasswordAsync(......);
//............
//If failed
fail = 1;
HttpContext.Response.Cookies.Append("LoginInfo", fail.ToString());
return View();
}
Result:
Tried with a middleware;
app.Use(async (context, next) =>
{
string failure;
int fail = 0;
context.Request.Cookies.TryGetValue("LoginFailure", out failure);
fail = Convert.ToInt32(failure);
if (fail >= 3&& context.Request.Path.Value.Contains("Login"))
{
context.Response.Redirect("/Home/Wait");
}
await next.Invoke();
if (context.Items.ContainsKey("Fail"))
{
fail = 1;
context.Response.Cookies.Append("LoginFailure", fail.ToString());
}
});