public async Task <IActionResult> Login(string email, string password, bool rememberMe) { var user = await _userManager.FindByEmailAsync(email); if (user == null) { ModelState.AddModelError(string.Empty, "Invalid login"); return(View()); } if (!user.EmailConfirmed) { ModelState.AddModelError(string.Empty, "Confirm your email first"); return(View()); } var passwordSignInResult = await _signInManager.PasswordSignInAsync(user, password, isPersistent : rememberMe, lockoutOnFailure : false); if (!passwordSignInResult.Succeeded) { await _userManager.AccessFailedAsync(user); ModelState.AddModelError(string.Empty, "Invalid login"); return(View()); } return(Redirect("~/")); }
public async Task <IActionResult> Login(LoginDTO model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var user = await userManager.FindByEmailAsync(model.Email); if (user == null) { ModelState.AddModelError(string.Empty, "The email is already registered."); return(BadRequest()); } var passwordSignInResult = await signInManager.PasswordSignInAsync(user, model.Password, true, false); if (!passwordSignInResult.Succeeded) { await userManager.AccessFailedAsync(user); ModelState.AddModelError(string.Empty, "Invalid login"); return(BadRequest()); } return(Ok(new { message = "Logged in success!", userEmail = model.Email }));; }
public async Task<IActionResult> LoginUser([FromBody] LoginModel model) { var user = await userManager.FindByEmailAsync(model.Email); if (user == null) { return NotFound("User not found"); } if (await userManager.IsLockedOutAsync(user)) { // add email logic to notify user return BadRequest("User has been locked out for 10 minutes"); } else if (!await userManager.CheckPasswordAsync(user, model.Password)) { await userManager.AccessFailedAsync(user); return BadRequest("Incorrect password"); } await userManager.ResetAccessFailedCountAsync(user); var appToken = await jwtFactory.GenerateEncodedToken(user); var newRefreshToken = jwtFactory.GenerateRefreshToken(); user.RefreshToken = newRefreshToken; await userManager.UpdateAsync(user); return new ObjectResult(new { token = appToken, refreshToken = newRefreshToken }); }
public async Task <bool> ValidateUser(LoginDTO userForAuth) { _user = await _userManager.FindByNameAsync(userForAuth.UserName); if (_user == null) { _message = "User not found"; return(false); } bool checkPass = await _userManager.CheckPasswordAsync(_user, userForAuth.Password); if (!checkPass) { await _userManager.AccessFailedAsync(_user); if (await _userManager.IsLockedOutAsync(_user)) { _message = $"Your account is locked out contact admin"; return(false); } _message = "Invalid password."; return(false); } await _userManager.ResetAccessFailedCountAsync(_user); await _userManager.SetLockoutEndDateAsync(_user, new DateTime(2000, 1, 1)); return(true); }
public async Task AccessFailedCount(bool includeRoles) { UserStore <ApplicationUser, IdentityRole, IdentityCloudContext> store = CreateUserStore(includeRoles); UserManager <ApplicationUser> manager = CreateUserManager(includeRoles); var user = await CreateTestUser <ApplicationUser>(includeRoles); var taskUser = await manager.GetAccessFailedCountAsync(user); Assert.AreEqual <int>(user.AccessFailedCount, taskUser); var taskAccessFailed = await manager.AccessFailedAsync(user); Assert.IsTrue(taskAccessFailed.Succeeded, string.Concat(taskAccessFailed.Errors.Select(e => e.Code).ToArray())); user = await manager.FindByIdAsync(user.Id); var taskAccessReset = await manager.ResetAccessFailedCountAsync(user); Assert.IsTrue(taskAccessReset.Succeeded, string.Concat(taskAccessReset.Errors)); await Assert.ThrowsExceptionAsync <ArgumentNullException>(async() => await store.GetAccessFailedCountAsync(null)); await Assert.ThrowsExceptionAsync <ArgumentNullException>(async() => await store.IncrementAccessFailedCountAsync(null)); await Assert.ThrowsExceptionAsync <ArgumentNullException>(async() => await store.ResetAccessFailedCountAsync(null)); }
public async Task <IActionResult> Login(Session session) { var user = await _userManager.FindByEmailAsync(session.Email); if (user == null) { ModelState.AddModelError(string.Empty, "Invalid login"); return(View("Login", session)); } if (!user.EmailConfirmed) { ModelState.AddModelError(string.Empty, "Confirm your email first"); return(View("Login")); } SignInResult passwordSignInResult = await _signInManager.PasswordSignInAsync(user, session.Password, isPersistent : session.RememberMe, lockoutOnFailure : false); if (!passwordSignInResult.Succeeded) { await _userManager.AccessFailedAsync(user); ModelState.AddModelError(string.Empty, "Invalid login"); return(View("Login", session)); } if (session.RedirectUrl != null) { return(Redirect(session.RedirectUrl)); } return(RedirectToAction("Index", "Home")); }
public async Task <IActionResult> Login(LoginData login) { // This might be used if you want to save an Auth cookie // var result = await signInManager.PasswordSignInAsync(login.Username, login.Password, false, false); var user = await userManager.FindByNameAsync(login.Username); if (user != null) { var result = await userManager.CheckPasswordAsync(user, login.Password); if (result) { return(Ok(new { UserId = user.Id, Token = await CreateTokenAsync(user), })); } await userManager.AccessFailedAsync(user); } return(Unauthorized()); }
public async void LockUserOut() { // Create a user and enable lockout var user = new User(Guid.NewGuid()) { UserName = "******" }; await UserManager.CreateAsync(user); await UserManager.SetLockoutEnabledAsync(user.Id, true); // Should be able to record a failed login IdentityResult result = await UserManager.AccessFailedAsync(user.Id); result.ShouldBeSuccess(); // Since the test setup uses one as the threshold for lockouts, the user should now be locked out bool isLockedOut = await UserManager.IsLockedOutAsync(user.Id); isLockedOut.Should().BeTrue(); // Since the test setup set the lockout period to 15 mins, the lockout end date should be approximately 15 mins from now DateTimeOffset lockoutEndDate = await UserManager.GetLockoutEndDateAsync(user.Id); lockoutEndDate.Should().BeCloseTo(DateTimeOffset.UtcNow.Add(15.Minutes()), precision: 1000); // 1000 == Within 1 second }
public override Task <bool> TryAuthenticateAsync(string userNameOrEmailAddress, string plainPassword, Tenant tenant) { var user = _userRepository.GetAll().FirstOrDefault(x => x.UserName.Equals(userNameOrEmailAddress, StringComparison.InvariantCultureIgnoreCase) || x.EmailAddress.Equals(userNameOrEmailAddress, StringComparison.InvariantCultureIgnoreCase)); if (user == null || !string.IsNullOrWhiteSpace(user.Password)) { return(Task.FromResult(false)); } else { var passwordOk = BCrypt.Net.BCrypt.Verify(plainPassword, user.PasswordOrig); if (passwordOk) { _userManager.ResetAccessFailedCountAsync(user); var newHash = _userManager.PasswordHasher.HashPassword(user, plainPassword); user.Password = newHash; return(Task.FromResult(true)); } else { _userManager.AccessFailedAsync(user); return(Task.FromResult(false)); } } }
public async Task <IActionResult> Login(LoginVM vm) { if (ModelState.IsValid) { var user = await _userManagerService.FindByNameAsync(vm.UserName); if (user != null && !await _userManagerService.IsLockedOutAsync(user)) { if (await _userManagerService.CheckPasswordAsync(user, vm.Password)) { //if (!await _userManagerService.IsEmailConfirmedAsync(user)) //{ // ModelState.AddModelError("", "Email não confirmado!!"); // return View(); //} //await _userManagerService.ResetAccessFailedCountAsync(user); await _signInManager.SignInAsync(user, isPersistent : false); return(RedirectToAction("Index", "Home")); } await _userManagerService.AccessFailedAsync(user); if (await _userManagerService.IsLockedOutAsync(user)) { // email user, notifying them of lockout } } ModelState.AddModelError("", "Nome ou senha incorretos!"); } return(View()); }
public async Task <(Result result, Guid userId)> SignIn(string email, string password) { var user = await _dbContext.Users .Where(u => u.Email == email) .SingleOrDefaultAsync(); if (user == null) { return(Result.Failure("User not found. Try again with valid email and password."), Guid.Empty); } if (await _userManager.IsLockedOutAsync(user)) { return(Result.Failure("Account has been locked out due to many failed log-in attempts"), Guid.Empty); } var validPass = await _userManager.CheckPasswordAsync(user, password); if (!validPass) { await _userManager.AccessFailedAsync(user); return(Result.Failure("Invalid password."), Guid.Empty); } //email confirmation return(Result.Success(), Guid.Parse(user.Id)); }
public virtual async Task <JwtSignInResult> TwoFactorSignInAsync(string provider, string code, bool rememberClient = false) { if (rememberClient) { throw new NotSupportedException(nameof(rememberClient)); } var twoFactorInfo = RetrieveTwoFactorInfoAsync(); if (twoFactorInfo == null || twoFactorInfo.UserId == null) { return(JwtSignInResult.Failed()); } var user = await UserManager.FindByIdAsync(twoFactorInfo.UserId); if (user == null) { return(JwtSignInResult.Failed()); } var error = await PreSignInCheck(user); if (error != null) { return(error); } if (await UserManager.VerifyTwoFactorTokenAsync(user, provider, code)) { return(await DoTwoFactorSignInAsync(user, twoFactorInfo, rememberClient)); } // If the token is incorrect, record the failure which also may cause the user to be locked out await UserManager.AccessFailedAsync(user); return(JwtSignInResult.Failed()); }
public void AccessFailedCount() { UserStore <ApplicationUser, IdentityRole, IdentityCloudContext> store = CreateUserStore(); UserManager <ApplicationUser> manager = CreateUserManager(); var user = CreateTestUser <ApplicationUser>(); var taskUser = manager.GetAccessFailedCountAsync(user); taskUser.Wait(); Assert.AreEqual <int>(user.AccessFailedCount, taskUser.Result); var taskAccessFailed = manager.AccessFailedAsync(user); taskAccessFailed.Wait(); Assert.IsTrue(taskAccessFailed.Result.Succeeded, string.Concat(taskAccessFailed.Result.Errors.Select(e => e.Code).ToArray())); var userTaskFindById = manager.FindByIdAsync(user.Id); userTaskFindById.Wait(); user = userTaskFindById.Result; var taskAccessReset = manager.ResetAccessFailedCountAsync(user); taskAccessReset.Wait(); Assert.IsTrue(taskAccessReset.Result.Succeeded, string.Concat(taskAccessReset.Result.Errors)); Assert.ThrowsException <ArgumentNullException>(() => store.GetAccessFailedCountAsync(null).Wait()); Assert.ThrowsException <ArgumentNullException>(() => store.IncrementAccessFailedCountAsync(null).Wait()); Assert.ThrowsException <ArgumentNullException>(() => store.ResetAccessFailedCountAsync(null).Wait()); }
public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context) { var user = await _userManager.FindByNameAsync(context.UserName); if (user != null) { if (await _signInManager.CanSignInAsync(user)) { if (_userManager.SupportsUserLockout && await _userManager.IsLockedOutAsync(user)) { context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "User Locked Out"); } else if (await _userManager.CheckPasswordAsync(user, context.Password)) { if (_userManager.SupportsUserLockout) { await _userManager.ResetAccessFailedCountAsync(user); } var sub = await _userManager.GetUserIdAsync(user); context.Result = new GrantValidationResult(sub, AuthenticationMethods.Password); } else if (_userManager.SupportsUserLockout) { await _userManager.AccessFailedAsync(user); } } } }
/// <inheritdoc /> public override async Task <SignInResult> TwoFactorSignInAsync(string provider, string code, bool isPersistent, bool rememberClient) { // borrowed from https://github.com/dotnet/aspnetcore/blob/master/src/Identity/Core/src/SignInManager.cs#L552 // replaced in order to use a custom auth type and to implement logging/events var twoFactorInfo = await RetrieveTwoFactorInfoAsync(); if (twoFactorInfo == null || twoFactorInfo.UserId == null) { return(SignInResult.Failed); } var user = await UserManager.FindByIdAsync(twoFactorInfo.UserId); if (user == null) { return(SignInResult.Failed); } var error = await PreSignInCheck(user); if (error != null) { return(error); } if (await UserManager.VerifyTwoFactorTokenAsync(user, provider, code)) { await DoTwoFactorSignInAsync(user, twoFactorInfo, isPersistent, rememberClient); return(await HandleSignIn(user, user?.UserName, SignInResult.Success)); } // If the token is incorrect, record the failure which also may cause the user to be locked out await UserManager.AccessFailedAsync(user); return(await HandleSignIn(user, user?.UserName, SignInResult.Failed)); }
public async Task <SignInStatus> TwoFactorSignIn(string provider, string code, bool isPersistent, bool rememberBrowser) { var userId = await GetVerifiedUserIdAsync(); if (userId == null) { return(SignInStatus.Failure); } var user = await UserManager.FindByIdAsync(userId); if (user == null) { return(SignInStatus.Failure); } if (await UserManager.IsLockedOutAsync(user.Id)) { return(SignInStatus.LockedOut); } if (await UserManager.VerifyTwoFactorTokenAsync(user.Id, provider, code)) { // When token is verified correctly, clear the access failed count used for lockout await UserManager.ResetAccessFailedCountAsync(user.Id); await SignInAsync(user, isPersistent, rememberBrowser); return(SignInStatus.Success); } // If the token is incorrect, record the failure which also may cause the user to be locked out await UserManager.AccessFailedAsync(user.Id); return(SignInStatus.Failure); }
/// <summary> /// Attempts a password sign in for a user. /// </summary> /// <param name="user">The user to sign in.</param> /// <param name="password">The password to attempt to sign in with.</param> /// <param name="lockoutOnFailure">Flag indicating if the user account should be locked if the sign in fails.</param> /// <returns>The task object representing the asynchronous operation containing the <see name="SignInResult"/> /// for the sign-in attempt.</returns> /// <returns></returns> public virtual async Task <SignInResult> CheckPasswordSignInAsync(TUser user, string password, bool lockoutOnFailure) { if (user == null) { throw new ArgumentNullException(nameof(user)); } var error = await PreSignInCheck(user); if (error != null) { return(error); } if (await UserManager.CheckPasswordAsync(user, password)) { await ResetLockout(user); return(SignInResult.Success); } Logger.LogWarning(2, "User {userId} failed to provide the correct password.", await UserManager.GetUserIdAsync(user)); if (UserManager.SupportsUserLockout && lockoutOnFailure) { // If lockout is requested, increment access failed count which might lock out the user await UserManager.AccessFailedAsync(user); if (await UserManager.IsLockedOutAsync(user)) { return(await LockedOut(user)); } } return(SignInResult.Failed); }
/// <summary> /// Validates the two factor sign in code and creates and signs in the user, as an asynchronous operation. /// </summary> /// <param name="provider">The two factor authentication provider to validate the code against.</param> /// <param name="code">The two factor authentication code to validate.</param> /// <param name="isPersistent">Flag indicating whether the sign-in cookie should persist after the browser is closed.</param> /// <param name="rememberClient">Flag indicating whether the current browser should be remember, suppressing all further /// two factor authentication prompts.</param> /// <returns>The task object representing the asynchronous operation containing the <see name="SignInResult"/> /// for the sign-in attempt.</returns> public virtual async Task <SignInResult> TwoFactorSignInAsync(string provider, string code, bool isPersistent, bool rememberClient) { var twoFactorInfo = await RetrieveTwoFactorInfoAsync(); if (twoFactorInfo == null || twoFactorInfo.UserId == null) { return(SignInResult.Failed); } var user = await UserManager.FindByIdAsync(twoFactorInfo.UserId); if (user == null) { return(SignInResult.Failed); } var error = await PreSignInCheck(user); if (error != null) { return(error); } if (await UserManager.VerifyTwoFactorTokenAsync(user, provider, code)) { await DoTwoFactorSignInAsync(user, twoFactorInfo, isPersistent, rememberClient); return(SignInResult.Success); } // If the token is incorrect, record the failure which also may cause the user to be locked out await UserManager.AccessFailedAsync(user); return(SignInResult.Failed); }
public async Task <SignInStatus> PasswordSignIn(string userName, string password, bool isPersistent, bool shouldLockout) { var user = await UserManager.FindByNameAsync(userName); if (user == null) { return(SignInStatus.Failure); } if (await UserManager.IsLockedOutAsync(user.Id)) { return(SignInStatus.LockedOut); } if (await UserManager.CheckPasswordAsync(user, password)) { return(await SignInOrTwoFactor(user, isPersistent)); } if (shouldLockout) { // If lockout is requested, increment access failed count which might lock out the user await UserManager.AccessFailedAsync(user.Id); if (await UserManager.IsLockedOutAsync(user.Id)) { return(SignInStatus.LockedOut); } } return(SignInStatus.Failure); }
public async Task <Response <TIdentity> > CheckCredentials(string username, string password) { _logger.LogInformation("Check credentials for {username}", username); var user = await _userManager.FindByNameAsync(username); if (user == null) { return(Response.ForError("Invalid credentials.")); } Response lockout; if ((lockout = await GetLockedStatus(user)) != null) { return(lockout); } if (await _userManager.CheckPasswordAsync(user, password)) { await _userManager.ResetAccessFailedCountAsync(user); _logger.LogInformation("Credentials valid for {username}, access failed count is reset.", username); return(Response <TIdentity> .ForSuccess(user)); } await _userManager.AccessFailedAsync(user); if ((lockout = await GetLockedStatus(user)) != null) { return(lockout); } return(Response.ForError("Invalid credentials.")); }
public override async Task <SignInStatus> TwoFactorSignInAsync(string provider, string code, bool isPersistent, bool rememberBrowser) { var userId = await GetVerifiedUserIdAsync(); if (userId == null) { return(SignInStatus.Failure); } var user = await UserManager.FindByIdAsync(userId); if (user == null) { return(SignInStatus.Failure); } if (await UserManager.IsLockedOutAsync(user.Id)) { return(SignInStatus.LockedOut); } if (await UserManager.VerifyTwoFactorTokenAsync(user.Id, provider, code)) { await UserManager.ResetAccessFailedCountAsync(user.Id); await SignInAsync(user, isPersistent, rememberBrowser); return(SignInStatus.Success); } await UserManager.AccessFailedAsync(user.Id); return(SignInStatus.Failure); }
public override async Task <SignInStatus> PasswordSignInAsync(string userName, string password, bool isPersistent, bool shouldLockout) { if (UserManager == null) { return(SignInStatus.Failure); } var user = await UserManager.FindByNameAsync(userName).WithCurrentCulture(); if (user == null) { return(SignInStatus.Failure); } if (UserManager.SupportsUserLockout && await UserManager.IsLockedOutAsync(user.Id).WithCurrentCulture()) { return(SignInStatus.LockedOut); } if (UserManager.SupportsUserPassword && await UserManager.CheckPasswordAsync(user, password).WithCurrentCulture()) { return(await SignInOrTwoFactor(user, isPersistent).WithCurrentCulture()); } if (shouldLockout && UserManager.SupportsUserLockout) { // If lockout is requested, increment access failed count which might lock out the user await UserManager.AccessFailedAsync(user.Id).WithCurrentCulture(); if (await UserManager.IsLockedOutAsync(user.Id).WithCurrentCulture()) { return(SignInStatus.LockedOut); } } return(SignInStatus.Failure); }
public async Task <SignInStatus> SignInAsync(string userName, string password, bool rememberMe) { var user = await UserManager.FindByNameAsync(userName); if (user == null) { return(SignInStatus.Failure); } if (await UserManager.IsLockedOutAsync(user.Id)) { return(SignInStatus.LockedOut); } if (!await UserManager.CheckPasswordAsync(user, password)) { await UserManager.AccessFailedAsync(user.Id); if (await UserManager.IsLockedOutAsync(user.Id)) { return(SignInStatus.LockedOut); } return(SignInStatus.Failure); } if (!await UserManager.IsEmailConfirmedAsync(user.Id)) { return(SignInStatus.RequiresVerification); } await base.SignInAsync(user, rememberMe, false); return(SignInStatus.Success); }
public async Task <IActionResult> Login(LoginModel model) { if (ModelState.IsValid) { var user = await _userManager.FindByNameAsync(model.UserName); if (user != null && !await _userManager.IsLockedOutAsync(user)) { if (await _userManager.CheckPasswordAsync(user, model.Password)) { if (!await _userManager.IsEmailConfirmedAsync(user)) { ModelState.AddModelError("", "E-mail não está válido!"); return(View()); } await _userManager.ResetAccessFailedCountAsync(user); if (await _userManager.GetTwoFactorEnabledAsync(user)) { var validator = await _userManager.GetValidTwoFactorProvidersAsync(user); if (validator.Contains("Email")) { var token = await _userManager.GenerateTwoFactorTokenAsync(user, "Email"); System.IO.File.WriteAllText("email2sv.txt", token); await HttpContext.SignInAsync(IdentityConstants.TwoFactorUserIdScheme, Store2FA(user.Id, "Email")); return(RedirectToAction("TwoFactor")); } } var principal = await _userClaimsPrincipalFactory.CreateAsync(user); await HttpContext.SignInAsync(IdentityConstants.ApplicationScheme, principal); //var signInResult = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, false, false); //if (signInResult.Succeeded) //{ return(RedirectToAction("About")); } await _userManager.AccessFailedAsync(user); if (await _userManager.IsLockedOutAsync(user)) { // Email deve ser enviado com sugestão de mudança de Senha! } } ModelState.AddModelError("", "Usuário ou Senha Invalida"); } return(View()); }
/// <summary> /// Validate user by username and password /// </summary> /// <param name="username">username</param> /// <param name="password">password</param> /// <param name="lockoutOnFailure">to disable the lockout feature, use false</param> /// <returns></returns> public async Task <IdentityResult <UserWithRoles> > GetUserByUsername(string username, string password, bool lockoutOnFailure) { var res = new IdentityResult <UserWithRoles>(); var user = await _userManager.FindByNameAsync(username); if (user == null) { res.Errors = new[] { "User with this username not found" }; res.ErrorType = ErrorType.NotFound; return(res); } var userHasValidPassword = await _userManager.CheckPasswordAsync(user, password); if (!userHasValidPassword) { res.Errors = new[] { "Invalid password" }; if (_userManager.SupportsUserLockout && lockoutOnFailure) { // If lockout is requested, increment access failed count which might lock out the user await _userManager.AccessFailedAsync(user); if (await _userManager.IsLockedOutAsync(user)) { res.Errors = new[] { "Invalid password", "Account is locked out" }; } } res.ErrorType = ErrorType.InvalidParameters; return(res); } // account is still in lockout period if (_userManager.SupportsUserLockout && user.LockoutEnabled && user.LockoutEnd.HasValue) { if (user.LockoutEnd.Value.DateTime > DateTime.UtcNow) { res.Errors = new[] { "Account is still locked out" }; res.ErrorType = ErrorType.InvalidParameters; return(res); } } await _userManager.ResetLockout(user); var details = new UserWithRoles { User = user, Roles = await _userManager.GetRolesAsync(user) }; res.Object = details; res.Success = true; return(res); }
public async Task <IActionResult> LoginWith2fa([FromBody] LoginWithAuthenticatorViewModel model) { var userId = await RetrieveBearerTwoFactorUserIdAsync(); if (string.IsNullOrEmpty(userId)) { return(BadRequest(new ApiBadRequestResponse(ModelState, "Unable to login with 2FA."))); } var user = await _userManager.FindByIdAsync(userId); if (user is null) { _logger.LogWarning("Unable to load user with ID {UserId}.", userId); return(BadRequest(new ApiBadRequestResponse(ModelState, "Unable to login with 2FA."))); } if (!await _signInManager.CanSignInAsync(user) || (_userManager.SupportsUserLockout && await _userManager.IsLockedOutAsync(user))) { _logger.LogWarning("Unable to sign in user with ID {UserId}.", userId); return(BadRequest(new ApiBadRequestResponse(ModelState, "The specified user cannot sign in."))); } // Strip spaces and hypens var pin = model.Code.Replace(" ", string.Empty).Replace("-", string.Empty); var provider = _userManager.Options.Tokens.AuthenticatorTokenProvider ?? TokenOptions.DefaultAuthenticatorProvider; var verified = await _userManager.VerifyTwoFactorTokenAsync(user, provider, pin); if (verified) { // When token is verified correctly, clear the access failed count used for lockout if (_userManager.SupportsUserLockout) { await _userManager.ResetAccessFailedCountAsync(user); } _logger.LogInformation("User with ID {UserId} logged in with 2FA.", user.Id); if (model.RememberDevice) { // TODO: Implement 2FA Remember Device Cookie //var jwt = await GetUserTokenAsync(user, TokenScheme.TwoFactorRememberMe); //return Ok(new ApiOkResponse(jwt).Result); throw new NotSupportedException("TwoFactorRememberMeScheme Token is not supported!"); } var jwt = await GetUserTokenAsync(user); return(Ok(new ApiOkResponse(jwt).Result)); } // If the token is incorrect, record the failure which also may cause the user to be locked out (protect against brute force attacks) await _userManager.AccessFailedAsync(user); _logger.LogWarning("Invalid authenticator code entered for user with ID {UserId}.", user.Id); return(Unauthorized(new ApiUnauthorizedResponse("Invalid authenticator code."))); }
/// <summary> /// Increments the access failed count for the user /// </summary> /// <param name="manager"></param> /// <param name="userId"></param> /// <returns></returns> public static IdentityResult AccessFailed <TUser, TKey>(this UserManager <TUser, TKey> manager, TKey userId) where TUser : class, IUser <TKey> where TKey : IEquatable <TKey> { if (manager == null) { throw new ArgumentNullException("manager"); } return(AsyncHelper.RunSync(() => manager.AccessFailedAsync(userId))); }
public async Task <(Result Result, string UserId)> AddToUserAccessFailedAsync(string userId) { ApplicationUser user = await GetUserByIdAsync(userId); IdentityResult result = await _userManager.AccessFailedAsync(user); return(result.ToApplicationResult(), user.Id); }
public async Task CanIncreaseAccessFailedCount() { var user = await _userManager.FindByNameAsync("test"); var result = await _userManager.AccessFailedAsync(user); Assert.True(result.Succeeded); }
public async Task <IActionResult> Login(LoginViewModel model, string returnUrl = null) { LoggerController.AddBeginMethodLog(this.GetType().Name, MethodBase.GetCurrentMethod().Name); s.Restart(); ViewData["ReturnUrl"] = returnUrl; if (ModelState.IsValid) { var result = await _signInManager.PasswordSignInAsync(model. Email, model.Password, model.RememberMe, lockoutOnFailure : true); if (result.Succeeded) { _logger.LogInformation("User logged in."); s.Stop(); LoggerController.AddEndMethodLog(this.GetType().Name, MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds); return(RedirectToLocal(returnUrl)); } if (result.RequiresTwoFactor) { s.Stop(); LoggerController.AddEndMethodLog(this.GetType().Name, MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds); return(RedirectToAction(nameof(LoginWith2fa), new { returnUrl, model.RememberMe })); } if (result.IsLockedOut) { _logger.LogWarning("User account locked out."); s.Stop(); LoggerController.AddEndMethodLog(this.GetType().Name, MethodBase. GetCurrentMethod().Name, s.ElapsedMilliseconds); return(RedirectToAction(nameof(Lockout))); } else { ApplicationUser user = await _userManager.FindByEmailAsync(model.Email); if (user != null) { await _userManager.AccessFailedAsync(user); } ModelState.AddModelError(string.Empty, "Niepoprawne dane logowania."); s.Stop(); LoggerController.AddEndMethodLog(this.GetType().Name, MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds); return(View(model)); } } s.Stop(); LoggerController.AddEndMethodLog(this.GetType().Name, MethodBase. GetCurrentMethod().Name, s.ElapsedMilliseconds); return(View(model)); }
public void AccessFailedCount() { using (UserStore<IdentityUser> store = new UserStore<IdentityUser>()) { using (UserManager<IdentityUser> manager = new UserManager<IdentityUser>(store)) { manager.MaxFailedAccessAttemptsBeforeLockout = 2; var user = CreateTestUser(); var taskUser = manager.GetAccessFailedCountAsync(user.Id); taskUser.Wait(); Assert.AreEqual<int>(user.AccessFailedCount, taskUser.Result, "AccessFailedCount not equal"); var taskAccessFailed = manager.AccessFailedAsync(user.Id); taskAccessFailed.Wait(); Assert.IsTrue(taskAccessFailed.Result.Succeeded, string.Concat(taskAccessFailed.Result.Errors)); user = manager.FindById(user.Id); var taskAccessReset = manager.ResetAccessFailedCountAsync(user.Id); taskAccessReset.Wait(); Assert.IsTrue(taskAccessReset.Result.Succeeded, string.Concat(taskAccessReset.Result.Errors)); try { var task = store.GetAccessFailedCountAsync(null); task.Wait(); } catch (Exception ex) { Assert.IsNotNull(ex, "Argument exception not raised"); } try { var task = store.IncrementAccessFailedCountAsync(null); task.Wait(); } catch (Exception ex) { Assert.IsNotNull(ex, "Argument exception not raised"); } try { var task = store.ResetAccessFailedCountAsync(null); task.Wait(); } catch (Exception ex) { Assert.IsNotNull(ex, "Argument exception not raised"); } } } }