public async Task <IActionResult> OnPostAsync(string returnUrl = null) { if (!ModelState.IsValid) { return(Page()); } User user = await userService.SignInManager.GetTwoFactorAuthenticationUserAsync(); if (user is null) { throw new InvalidOperationException(Messages.EXCEPTION_2FA_LOADUSER_FAILED); } string recoveryCode = RecoveryCode.Replace(" ", string.Empty); Microsoft.AspNetCore.Identity.SignInResult result = await userService.SignInManager.TwoFactorRecoveryCodeSignInAsync(recoveryCode); if (result.Succeeded) { logger.LogInformation(Messages.LOGGER_INFO_USER_LOGGED_RECOVERYCODE, user.Id); return(LocalRedirect(returnUrl ?? Url.Content("~/"))); } if (result.IsLockedOut) { logger.LogWarning(Messages.LOGGER_WARN_USER_LOCKEDOUT, user.Id); return(RedirectToPage("./Lockout")); } else { logger.LogWarning(Messages.LOGGER_WARN_USER_WRONGRECOVERYCODE, user.Id); ModelState.AddModelError(string.Empty, Messages.MODELSTATEERROR_INVALIDRECOVERYCODE); return(Page()); } }
public async Task <IActionResult> Login(LoginRequest loginRequest, string returnUrl = null) { if (!ModelState.IsValid) { return(RedirectToAction(nameof(Login))); } returnUrl = returnUrl ?? Url.Content("~/"); Microsoft.AspNetCore.Identity.SignInResult result = await _loginService.Login(GetIp(), GetSessionCode(), loginRequest); if (result.Succeeded) { return(Redirect(returnUrl)); } else if (result.RequiresTwoFactor) { return(RedirectToAction("LoginWith2fa", new { RememberMe = loginRequest.RememberMe, ReturnUrl = returnUrl })); } else if (result.IsLockedOut) { return(Redirect(PagePath.LOCKOUT)); } else { ViewBag.RetunrUrl = returnUrl; ViewBag.RegistrationEnabled = _identityManagementEndpoints.RegisterEnabled; ModelState.AddModelError(string.Empty, "Invalid login attempt"); return(View()); } }
public async Task <IActionResult> OnPostAsync(string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/"); if (ModelState.IsValid) { Microsoft.AspNetCore.Identity.SignInResult result = await userManager.SignIn(HttpContext, Input.Username, Input.Password, Input.RememberMe, Input.TwoFa); if (result.Succeeded) { _logger.LogInformation("User logged in."); return(LocalRedirect(returnUrl)); } if (result.RequiresTwoFactor) { ModelState.AddModelError(string.Empty, "Two-Factor is needed"); Input.ShowTwoFa = true; return(Page()); } if (result.IsLockedOut) { _logger.LogWarning("User account locked out."); return(RedirectToPage("./Lockout")); } else { ModelState.AddModelError(string.Empty, "Username or password wrong."); return(Page()); } } // If we got this far, something failed, redisplay form return(Page()); }
public async Task<IActionResult> LoginWith2fa(LoginWith2faRequest loginWith2FaRequest, string returnUrl = null) { if (!ModelState.IsValid) { return RedirectToAction(nameof(Login)); } returnUrl = returnUrl ?? Url.Content("~/"); Microsoft.AspNetCore.Identity.SignInResult result = await _loginService.LoginWith2fa(GetIp(), loginWith2FaRequest); if(result.Succeeded) { return LocalRedirect(returnUrl); } else if(result.IsLockedOut) { return LocalRedirect(PagePath.LOCKOUT); } else { ViewBag.RetunrUrl = returnUrl; ModelState.AddModelError(string.Empty, "Invalid authenticator code"); return View(); } }
public async Task<IActionResult> Login(LoginRequest loginRequest, string returnUrl = null) { if (!ModelState.IsValid) { LoginViewModel loginViewModel = await _accountDataService.GetLoginViewModel(returnUrl); return View(loginViewModel); } returnUrl = returnUrl ?? Url.Content("~/"); Microsoft.AspNetCore.Identity.SignInResult result = await _loginService.Login(GetIp(), GetSessionCode(), loginRequest); if(result.Succeeded) { return LocalRedirect(returnUrl); } else if(result.RequiresTwoFactor) { return RedirectToAction(nameof(LoginWith2fa), new { RememberMe = loginRequest.RememberMe, ReturnUrl = returnUrl}); } else if(result.IsLockedOut) { return LocalRedirect(PagePath.LOCKOUT); } else { LoginViewModel loginViewModel = await _accountDataService.GetLoginViewModel(returnUrl); ModelState.AddModelError(string.Empty, "Invalid login attempt"); return View(loginViewModel); } }
public async Task <IActionResult> Login(LoginViewModel model, string returnUrl = null) { try { ValidateModelState(); SignInResult result = null; result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, true, true); if (result.IsLockedOut) { throw new BusinessException(MessageText.AccountLocked); } if (!result.Succeeded) { throw new BusinessException(MessageText.InvalidLoginAttempt); } } catch (BusinessException ex) { SetError(ex); model.Password = ""; return(View(model)); } return(RedirectToLocal(returnUrl)); }
public async Task <IActionResult> Register(AddUserViewModel model) { if (ModelState.IsValid) { UserEntity user = await _userHelper.AddUserAsync(model, TipoUsuario.Usuario); if (user == null) { ModelState.AddModelError(string.Empty, "Este Email ya esta registrado."); return(View(model)); } LoginViewModel loginViewModel = new LoginViewModel { Contraseña = model.Contraseña, Recuerdame = false, Usuario = model.Usuario }; Microsoft.AspNetCore.Identity.SignInResult result2 = await _userHelper.LoginAsync(loginViewModel); if (result2.Succeeded) { return(RedirectToAction("Index", "Home")); } } return(View(model)); }
public async Task <IActionResult> Login(LoginVM model, string returnUrl) { if (!ModelState.IsValid) { return(View(model)); } UserManager userManager = UserManager.Create(_dal.Database.GetConnectionString()); SignInManager signInManager = SignInManager.Create(userManager); // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, change to shouldLockout: true SignInResult signInResult = signInManager.PasswordSignIn(model.EmailAddress, model.Password.Secure(), false); if (signInResult.Succeeded) { ClaimsPrincipal userPrincipal = signInManager.CreateUserPrincipal(userManager.User); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, userPrincipal); return(redirectToLocal(returnUrl)); } if (signInResult.IsLockedOut) { return(View("Lockout")); } ModelState.AddModelError("", "Invalid Username or Password"); return(View(model)); }
private IActionResult GetAbpLoginResult(SignInResult result) { if (result.IsLockedOut) { return(StatusCode(StatusCodes.Status403Forbidden, new { result = L["LoginFailed"].Value, detail = L["UserLockedOutMessage"].Value })); } if (result.IsNotAllowed) { return(StatusCode(StatusCodes.Status403Forbidden, new { result = L["LoginFailed"].Value, detail = L["LoginIsNotAllowed"].Value })); } if (!result.Succeeded) { return(StatusCode(StatusCodes.Status401Unauthorized, new { result = L["LoginFailed"].Value, detail = L["InvalidUserNameOrPassword"].Value })); } return(Ok()); }
/// <summary> /// When user is not authenticated look for magic key in the header and log user in. /// </summary> /// <param name="filterContext"></param> public void OnAuthorization(AuthorizationFilterContext filterContext) { // See if the AllowAnonymous attribute has been used for the action and skip over. if (IsAllowAnonymous(filterContext.Filters) == false) { IdentityService identityService = BLL.Startup.IdentityService; // see if the user is already authenticated. if (filterContext.HttpContext.User.Identity.IsAuthenticated == true) { if (identityService.IsInRoles(filterContext.HttpContext.User, this.Roles) == false) { // The already logged in user is not allowed to access this page. filterContext.Result = new StatusCodeResult(StatusCodes.Status403Forbidden); } } else { // Check for the header token. string token = filterContext.HttpContext.Request.Headers[ApiAuthorizationController.HeaderTokenName].ToString(); if (token.IsNullOrEmpty() == false) { ApiLoginRepository loginRepo = (ApiLoginRepository)DAL.Startup.ApiLoginRepository; loginRepo.ClearExpiredLogins(ApiAuthorizationController.TimeoutHours); ApiSessionModel model = loginRepo.Fetch(token); if (model != null) { Microsoft.AspNetCore.Identity.SignInResult signInResult = (identityService.LoginAsync(new ApiLoginModel() { Email = model.Email, Password = model.Password }, mustBeInRole: "Api")).Result; if (signInResult.Succeeded == false) { filterContext.Result = new StatusCodeResult(StatusCodes.Status403Forbidden); } signInResult = null; } else { filterContext.Result = new StatusCodeResult(StatusCodes.Status403Forbidden); } model = null; loginRepo = null; } else { filterContext.Result = new StatusCodeResult(StatusCodes.Status403Forbidden); } } identityService = null; } }
public SignInResultCustom(Models.User user, Microsoft.AspNetCore.Identity.SignInResult result) { User = user; Succeeded = result.Succeeded; IsLockedOut = result.IsLockedOut; IsNotAllowed = result.IsNotAllowed; RequiresTwoFactor = result.RequiresTwoFactor; }
private static string ProcessErrorResult(Microsoft.AspNetCore.Identity.SignInResult result) { if (result.IsLockedOut) { return("Account Locked Out"); } return(result.IsNotAllowed ? "Login not allowed" : "Wrong Credentials"); }
private APIResponse OnSignInResultCheck(IServiceProvider services, Microsoft.AspNetCore.Identity.SignInResult result, DAL.Models.Identity.User user, JwtAudience audience, bool tfaRequired) { if (result != null) { if (result.Succeeded || result.RequiresTwoFactor) { // tfa token if (tfaRequired || result.RequiresTwoFactor) { return(APIResponse.Success( new AuthenticateView() { Token = JWT.CreateAuthToken( appConfig: AppConfig, user: user, audience: audience, area: JwtArea.Tfa ), TfaRequired = true, } )); } // new jwt salt UserAccount.GenerateJwtSalt(user, audience); DbContext.SaveChanges(); // auth token return(APIResponse.Success( new AuthenticateView() { Token = JWT.CreateAuthToken( appConfig: AppConfig, user: user, audience: audience, area: JwtArea.Authorized ), TfaRequired = false, } )); } if (result.IsLockedOut) { return(APIResponse.BadRequest(APIErrorCode.AccountLocked, "Too many unsuccessful attempts to sign in. Account is locked, try to sign in later")); } if (result.IsNotAllowed) { return(APIResponse.BadRequest(APIErrorCode.AccountEmailNotConfirmed, "Email is not confirmed yet")); } } // not found return(null); }
public async Task <ActionResult> Login([FromBody] ApiLoginModel model) { Repository.ClearExpiredLogins(TimeoutHours); if (ModelState.IsValid == true) { Microsoft.AspNetCore.Identity.SignInResult signInResult = await this.IdentityService.LoginAsync(model, mustBeInRole : "Api"); if (signInResult != null) { if (signInResult.Succeeded == true) { ApiSessionModel apiSessionModel = Repository.FetchByLogin(model); if (apiSessionModel != null) { apiSessionModel.SessionStarted = DateTime.Now; } else { // store username, password and email for later in in memory repo apiSessionModel = new ApiSessionModel() { Email = model.Email, Password = model.Password, Token = Guid.NewGuid().ToString().Replace("-", string.Empty), SessionStarted = DateTime.Now }; Repository.Create(apiSessionModel); } Repository.Save(); // return magic key Response.Headers.Add(new KeyValuePair <string, StringValues>(HeaderTokenName, apiSessionModel.Token)); return(Ok()); } else { return(new StatusCodeResult(403)); // forbidden } } else { return(new StatusCodeResult(403)); // forbidden } } else { return(new StatusCodeResult(403)); // forbidden } }
private async Task <IActionResult> TratarSignInResult(SignInResult result, CredenciaisDto credenciais) { if (result.Succeeded) { return(Ok(loginServico.GerarToken(credenciais.NomeUsuario))); } if (result.IsLockedOut) { return(await TratarLockout(credenciais.NomeUsuario, credenciais.Senha)); } return(Unauthorized()); }
public async Task <IActionResult> Login(Administrator model) { if (ModelState.IsValid) { Microsoft.AspNetCore.Identity.SignInResult result = await _accountRepository.SignInAsync(model); if (result.Succeeded) { return(RedirectToAction("Index")); } ModelState.AddModelError("", "用户名或密码错误"); } return(View(model)); }
public async Task <IActionResult> SignIn([FromBody] LoginViewModel loginViewModel) { Microsoft.AspNetCore.Identity.SignInResult signInResult = await _accountRepository.SignIn(loginViewModel.UserName, loginViewModel.Password, loginViewModel.RememberMe); if (signInResult.Succeeded) { var apiResponse = new ApiResponse(signInResult.Succeeded, new string[] { }); return(Ok(apiResponse)); } else { return(BadRequest("Invalid user name or password")); } }
public async Task <IActionResult> CreateToken([FromBody] LoginViewModel model) { if (ModelState.IsValid) { User user = await _userHelper.GetUserAsync(model.Username); if (user != null) { //valida si el user y el pass coinciden Microsoft.AspNetCore.Identity.SignInResult result = await _userHelper.ValidatePasswordAsync(user, model.Password); if (result.Succeeded) { //creamos una colecciòn de clains, tanto con el email y con un guid //para que sean ùnicos para cada token Claim[] claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, user.Email), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()) }; //obtenemos la llave y la encriptamos (Encoding) SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Tokens:Key"])); //encriptamos las credenciales con HmacSha256 SigningCredentials credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); //generamos token JwtSecurityToken token = new JwtSecurityToken( _configuration["Tokens:Issuer"], _configuration["Tokens:Audience"], claims, expires: DateTime.UtcNow.AddDays(99), signingCredentials: credentials); var results = new { token = new JwtSecurityTokenHandler().WriteToken(token), expiration = token.ValidTo, user }; return(Created(string.Empty, results)); //devuelve los resultados } } } return(BadRequest()); }
public async Task <IActionResult> Login(LoginViewModel model) { //siempre preguntar si el model es valido if (ModelState.IsValid) { Microsoft.AspNetCore.Identity.SignInResult result = await _userHelper.LoginAsync(model); if (result.Succeeded) { if (Request.Query.Keys.Contains("ReturnUrl")) { return(Redirect(Request.Query["ReturnUrl"].First())); } return(RedirectToAction("Index", "Home")); } ModelState.AddModelError(string.Empty, "User or password incorrect"); } return(View(model)); }
public async Task <IActionResult> CreateToken([FromBody] LoginViewModel model) { if (ModelState.IsValid) { User user = await _userHelper.GetUserAsync(model.Username); if (user != null) { Microsoft.AspNetCore.Identity.SignInResult result = await _userHelper.ValidatePasswordAsync(user, model.Password); if (result.Succeeded) { Claim[] claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, user.Email), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()) }; //TOKEM PARA ACCEDER AL API Y CONTROLAR EL TIEMPO QUE ESTE PUEDE EXPIRAR SIN ACTIVIDAD EN LA APLICACION ( SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Tokens:Key"])); SigningCredentials credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); JwtSecurityToken token = new JwtSecurityToken( _configuration["Tokens:Issuer"], _configuration["Tokens:Audience"], claims, expires: DateTime.UtcNow.AddDays(99), signingCredentials: credentials); var results = new { token = new JwtSecurityTokenHandler().WriteToken(token), expiration = token.ValidTo, user }; return(Created(string.Empty, results)); } } } return(BadRequest()); }
/// <summary> /// 获取登录结果 /// </summary> private SignInResult GetSignInResult(User user, Microsoft.AspNetCore.Identity.SignInResult signInResult) { if (signInResult.IsNotAllowed) { return(new SignInResult(SignInState.Failed, null, GreatWallResource.UserIsDisabled)); } if (signInResult.IsLockedOut) { return(new SignInResult(SignInState.Failed, null, GreatWallResource.LoginFailLock)); } if (signInResult.Succeeded) { return(new SignInResult(SignInState.Succeeded, user.Id.SafeString())); } if (signInResult.RequiresTwoFactor) { return(new SignInResult(SignInState.TwoFactor, user.Id.SafeString())); } return(new SignInResult(SignInState.Failed, null, GreatWallResource.InvalidAccountOrPassword)); }
public async Task <IActionResult> Login(LoginViewModel loginViewModel) { if (ModelState.IsValid) { Microsoft.AspNetCore.Identity.SignInResult result = await _userHelper.LoginAsync(loginViewModel); if (result.Succeeded) { if (Request.Query.Keys.Contains("ReturnUrl")) { return(Redirect(Request.Query["ReturnUrl"].First())); } return(RedirectToAction("Index", "Home")); } } ModelState.AddModelError(string.Empty, "Failed to login."); return(View(loginViewModel)); }
public async Task <IActionResult> Login([FromBody] LoginDTO model) { Microsoft.AspNetCore.Identity.SignInResult res = await _userService.Login(model); User user = await _userService.FindUserByEmail(model.email); if (res.Succeeded) { var token = await _userService.Authenticate(user); return(Ok(new { token })); } if (user == null) { return(BadRequest("InvalidUserNameOrPassword")); } return(BadRequest("LoginFailed")); }
public async Task <IActionResult> CreateToken([FromBody] LoginViewModel model) { if (ModelState.IsValid) { UserEntity user = await _userHelper.GetUserAsync(model.Username); if (user != null) { Microsoft.AspNetCore.Identity.SignInResult result = await _userHelper.ValidatePasswordAsync(user, model.Password); if (result.Succeeded) { object results = GetToken(user.Email); return(Created(string.Empty, results)); } } } return(BadRequest()); }
public async Task <IActionResult> OnPostAsync(bool rememberMe, string returnUrl = null) { if (!ModelState.IsValid) { return(Page()); } returnUrl = returnUrl ?? Url.Content("~/"); User user = await userService.SignInManager.GetTwoFactorAuthenticationUserAsync(); if (user is null) { throw new InvalidOperationException(EXCEPTION_2FA); } string authenticatorCode = TwoFactorCode.Replace(" ", string.Empty).Replace("-", string.Empty); Microsoft.AspNetCore.Identity.SignInResult result = await userService.SignInManager.TwoFactorAuthenticatorSignInAsync(authenticatorCode, rememberMe, RememberMachine); if (result.Succeeded) { logger.LogInformation(LOGGER_INFO_2FA_LOGIN, user.Id); return(LocalRedirect(returnUrl)); } else if (result.IsLockedOut) { logger.LogWarning(LOGGER_WARNING_USER_LOCKEDOUT, user.Id); return(RedirectToPage("./Lockout")); } else { logger.LogWarning(LOGGER_WARNING_USER_2FA_INVALIDATTEMPT, user.Id); ModelState.AddModelError(string.Empty, MESSAGE_ERROR_INVALID_2FACODE); return(Page()); } }
public async Task <IActionResult> Register(AddUserViewModel model) { if (ModelState.IsValid) { string path = string.Empty; if (model.PictureFile != null) { path = await _imageHelper.UploadImageAsync(model.PictureFile, "Users"); } Data.Entities.UserEntity user = await _userHelper.AddUserAsync(model, path); if (user == null) { ModelState.AddModelError(string.Empty, "This email is already used."); model.UserTypes = _combosHelper.GetComboRoles(); return(View(model)); } LoginViewModel loginViewModel = new LoginViewModel { Password = model.Password, RememberMe = false, Username = model.Username }; Microsoft.AspNetCore.Identity.SignInResult result2 = await _userHelper.LoginAsync(loginViewModel); if (result2.Succeeded) { return(RedirectToAction("Index", "Home")); } } model.UserTypes = _combosHelper.GetComboRoles(); return(View(model)); }
protected void SetSignInResult(Microsoft.AspNetCore.Identity.SignInResult result) => _signInManager.Setup(m => m.PasswordSignInAsync(_request.Login, _request.Password, _request.RememberMe, It.IsAny <bool>())) .ReturnsAsync(result);
public async Task <IActionResult> Register(AddUserViewModel model) { if (ModelState.IsValid) { string path = string.Empty; if (model.PictureFile != null) { path = await _imageHelper.UploadImageAsync(model.PictureFile, "Users"); } Data.Entities.UserEntity user = await _userHelper.AddUserAsync(model, path); if (user == null) { ModelState.AddModelError(string.Empty, "Este correo ya se encuentra registrado."); model.UserTypes = _combosHelper.GetComboRoles(); return(View(model)); } var myToken = await _userHelper.GenerateEmailConfirmationTokenAsync(user); var tokenLink = Url.Action("ConfirmEmail", "Account", new { userid = user.Id, token = myToken }, protocol: HttpContext.Request.Scheme); var response = _mailHelper.SendMail(model.Username, "Confirmación de correo electrónico", $"<h1>Correo de confirmación</h1>" + $"Para permitir al usuario, " + $"Por favor presione click en este enlace:" + $"</br></br><a href = \"{tokenLink}\">Confirmar Email</a>"); if (response.IsSuccess) { ViewBag.Message = "Se han enviado las instrucciones al correo."; return(View(model)); } ModelState.AddModelError(string.Empty, response.Message); LoginViewModel loginViewModel = new LoginViewModel { Password = model.Password, RememberMe = false, Username = model.Username }; Microsoft.AspNetCore.Identity.SignInResult result2 = await _userHelper.LoginAsync(loginViewModel); if (result2.Succeeded) { return(RedirectToAction("Index", "Home")); } } model.UserTypes = _combosHelper.GetComboRoles(); return(View(model)); }
public async Task <IActionResult> LoginAsync([FromBody] LoginViewModel model) { User user = await _userManager.FindByNameAsync(model.UserName); if (user != null) { if (user.IsActive) { Microsoft.AspNetCore.Identity.SignInResult result = await _signInManager.CheckPasswordSignInAsync(user, model.Password, false); if (result.Succeeded) { // Create the token string username = model.UserName; IList <string> roles = await _userManager.GetRolesAsync(user); List <Claim> roleClaims = new List <Claim>(); foreach (string roleName in roles) { Role role = await _roleManager.FindByNameAsync(roleName); IList <Claim> claims = await _roleManager.GetClaimsAsync(role); roleClaims.AddRange(claims); } string userRole = roles.Count > 0 ? roles[0] : ""; roleClaims.AddRange(new List <Claim> { new Claim("UserId", user.Id.ToString()), new Claim(JwtRegisteredClaimNames.Sub, user.Email ?? ""), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(JwtRegisteredClaimNames.UniqueName, user.UserName) }); SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_siteSettings.Tokens.Key)); SigningCredentials creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); JwtSecurityToken token = new JwtSecurityToken( _siteSettings.Tokens.Issuer, _siteSettings.Tokens.Audience, roleClaims, expires: DateTime.Now.AddDays(30), signingCredentials: creds); var results = new { token = new JwtSecurityTokenHandler().WriteToken(token), expiration = token.ValidTo }; return(Created("", results)); } if (result.IsNotAllowed) { return(BadRequest("Your registration is not approved, please re-register .")); } else if (result.IsLockedOut) { return(BadRequest("Your user is locked by the system administrator. Please contact support.")); } else { return(BadRequest("The password you entered for this username is incorrect.")); } } else { return(BadRequest("Your user has been disabled by the system administrator. Please contact support.")); } } return(BadRequest("Username not found")); }
public LoginForbiddenResult(IdentitySignInResult signInResult) { this.signInResult = signInResult; }