private async Task <ActionResult> SignInUser(IAccountViewModel viewModel, bool rememberMe = false) { var result = await _signInManager.PasswordSignInAsync( viewModel.Email, viewModel.Password, rememberMe, false); return(CheckSignInResult(null, result)); }
public async Task <ActionResult> Login(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return(View(model)); } // これは、アカウント ロックアウトの基準となるログイン失敗回数を数えません。 // パスワード入力失敗回数に基づいてアカウントがロックアウトされるように設定するには、shouldLockout: true に変更してください。 var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout : false); switch (result) { case SignInStatus.Success: return(RedirectToLocal(returnUrl)); case SignInStatus.LockedOut: return(View("Lockout")); case SignInStatus.RequiresVerification: return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe })); case SignInStatus.Failure: default: ModelState.AddModelError("", "無効なログイン試行です。"); return(View(model)); } }
public async Task <ActionResult> Login(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return(View(model)); } // This doen't count login failures towards lockout only two factor authentication // To enable password failures to trigger lockout, change to shouldLockout: true var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout : false); switch (result) { case SignInStatus.Success: var possibleUser = await UserManager.FindByEmailAsync(model.Email); if (null != possibleUser && possibleUser.MemberExpireAt.HasValue && possibleUser.MemberExpireAt.Value <= DateTime.UtcNow) { Session["IsMembershipExpired"] = "YES"; } return(RedirectToLocal(returnUrl)); case SignInStatus.LockedOut: return(View("Lockout")); case SignInStatus.RequiresVerification: return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl })); case SignInStatus.Failure: default: ModelState.AddModelError("", "Invalid login attempt."); return(View(model)); } }
public async Task <ActionResult> Login(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return(View(model)); } // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, change to shouldLockout: true var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout : false); switch (result) { case SignInStatus.Success: return(RedirectToLocal(returnUrl)); case SignInStatus.LockedOut: return(View("Lockout")); case SignInStatus.RequiresVerification: return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe })); case SignInStatus.Failure: default: ModelState.AddModelError("", "Invalid login attempt."); return(View(model)); } }
public async Task <ActionResult> Login(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return(View(model)); } // This doen't count login failures towards lockout only two factor authentication // To enable password failures to trigger lockout, change to shouldLockout: true var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout : false); switch (result) { case SignInStatus.Success: TempData["message"] = string.Format("{0} Logged-In: ", model.Email); return(RedirectToAction("Overview", "Dashboard")); case SignInStatus.LockedOut: return(View("Lockout")); case SignInStatus.RequiresVerification: return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe })); case SignInStatus.Failure: default: ModelState.AddModelError("", "Invalid login attempt."); return(View(model)); } }
public async Task <ActionResult> Login(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return(View(model)); } // Сбои при входе не приводят к блокированию учетной записи // Чтобы ошибки при вводе пароля инициировали блокирование учетной записи, замените на shouldLockout: true var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout : false); switch (result) { case SignInStatus.Success: return(RedirectToLocal(returnUrl)); case SignInStatus.LockedOut: return(View("Lockout")); case SignInStatus.RequiresVerification: return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe })); case SignInStatus.Failure: default: ModelState.AddModelError("", "Неудачная попытка входа."); return(View(model)); } }
public async Task <ActionResult> Login(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return(View(model)); } // 这不会计入到为执行帐户锁定而统计的登录失败次数中 // 若要在多次输入错误密码的情况下触发帐户锁定,请更改为 shouldLockout: true var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout : false); switch (result) { case SignInStatus.Success: return(RedirectToLocal(returnUrl)); case SignInStatus.LockedOut: return(View("Lockout")); case SignInStatus.RequiresVerification: return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe })); case SignInStatus.Failure: default: ModelState.AddModelError("", "无效的登录尝试。"); return(View(model)); } }
public async Task <ActionResult> Login(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return(View(model)); } // Anmeldefehler werden bezüglich einer Kontosperre nicht gezählt. // Wenn Sie aktivieren möchten, dass Kennwortfehler eine Sperre auslösen, ändern Sie in "shouldLockout: true". var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout : false); switch (result) { case SignInStatus.Success: return(RedirectToLocal(returnUrl)); case SignInStatus.LockedOut: return(View("Lockout")); case SignInStatus.RequiresVerification: return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe })); case SignInStatus.Failure: default: ModelState.AddModelError("", "Ungültiger Anmeldeversuch."); return(View(model)); } }
public virtual async Task <ActionResult> Zaloguj(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return(View(model)); } var user = await _userManager.FindByEmailAsync(model.Email); if (user != null) { if (!user.EmailConfirmed) { return(View("KontoNieaktywne", (object)model.Email)); } } var result = await _signInManager.PasswordSignInAsync(model.Email, model.PasswordLogin, model.RememberMe, false); switch (result) { case SignInStatus.Success: Session["username"] = user.Name; return(RedirectToLocal(returnUrl)); case SignInStatus.LockedOut: return(View(MVC.Shared.Views.Blokada)); default: ModelState.AddModelError("", "Nieprawidłowa nazwa użytkownika lub hasło"); return(View(model)); } }
public async Task <ActionResult> Login(LoginUserViewModel loginUser) { List <ErrorsModelException> errors = _authService.ValidateLoginForWeb(loginUser); if (!errors.Any()) { var signInResult = await _signInManager.PasswordSignInAsync(loginUser.Email, loginUser.Password, true, false); if (signInResult.Succeeded) { return(Redirect("/api-doc")); } if (signInResult.IsLockedOut) { ModelState.AddModelError("LockedOut", "You are locked out from system. Please Contact Administrator"); } if (signInResult.IsNotAllowed) { ModelState.AddModelError("NotAllowed", "You are not allowed to log in. Please Contact Administrator"); } if (signInResult.RequiresTwoFactor) { ModelState.AddModelError("RequireTwoFactor", "Require two factor authentication. Please Contact Administrator"); } ModelState.AddModelError("Error", "Invalid username and/or password."); return(View()); } return(View()); }
public async Task <ActionResult> Login(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return(View(model)); } // This doen't count login failures towards lockout only two factor authentication // To enable password failures to trigger lockout, change to shouldLockout: true var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout : false); var userManager = System.Web.HttpContext.Current.GetOwinContext().GetUserManager <ApplicationUserManager>(); var user = userManager.FindByEmail(model.Email); switch (result) { case SignInStatus.Success: Session["FirstName"] = user.FirstName; Session["LastName"] = user.LastName; return(RedirectToLocal(returnUrl)); case SignInStatus.LockedOut: return(View("Lockout")); case SignInStatus.RequiresVerification: return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl })); case SignInStatus.Failure: default: ModelState.AddModelError("", "Invalid login attempt."); return(View(model)); } }
public async Task <ActionResult> Login(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return(View(model)); } AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie, DefaultAuthenticationTypes.ApplicationCookie, DefaultAuthenticationTypes.TwoFactorCookie, DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie, DefaultAuthenticationTypes.ExternalBearer); // No cuenta los errores de inicio de sesión para el bloqueo de la cuenta // Para permitir que los errores de contraseña desencadenen el bloqueo de la cuenta, cambie a shouldLockout: true var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, false, shouldLockout : false); switch (result) { case SignInStatus.Success: Utils.WriteLogMessage(model.Email, "El usuario inicio sesión en la aplicación."); return(RedirectToLocal("/Dashboard/Index")); case SignInStatus.LockedOut: return(View("Lockout")); case SignInStatus.RequiresVerification: return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false })); case SignInStatus.Failure: default: ModelState.AddModelError("", "Intento de inicio de sesión no válido."); return(View(model)); } }
public async Task <ActionResult> Login(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return(View(model)); } // This doen't count login failures towards lockout only two factor authentication // To enable password failures to trigger lockout, change to shouldLockout: true var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout : false); switch (result) { case SignInStatus.Success: Session["UtilizadorID"] = db.Utilizadores.Where(c => c.Username.Equals(model.Email)).FirstOrDefault().ID; return(RedirectToLocal(returnUrl)); case SignInStatus.LockedOut: return(View("Lockout")); case SignInStatus.RequiresVerification: return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl })); case SignInStatus.Failure: default: ModelState.AddModelError("", "Tentativa de Login incorreta"); return(View(model)); } }
public async Task <ActionResult> Index(SignInViewModel viewModel) { if (!ModelState.IsValid) { return(View(viewModel)); } var result = await _signInManager.PasswordSignInAsync(viewModel.UserName, viewModel.Password, isPersistent : true, shouldLockout : true); switch (result) { case SignInStatus.Success: return(RedirectToAction("Index", "Home")); case SignInStatus.LockedOut: var user = await _userManager.FindByNameAsync(viewModel.UserName); if (user != null && await _userManager.CheckPasswordAsync(user, viewModel.Password)) { ModelState.AddModelError(string.Empty, "Your account is blocked."); } return(View(viewModel)); default: return(View(viewModel)); } }
public async Task <ActionResult> Login(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return(View(model)); } // No cuenta los errores de inicio de sesión para el bloqueo de la cuenta // Para permitir que los errores de contraseña desencadenen el bloqueo de la cuenta, cambie a shouldLockout: true var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout : false); switch (result) { case SignInStatus.Success: return(RedirectToLocal(returnUrl)); case SignInStatus.LockedOut: return(View("Lockout")); case SignInStatus.RequiresVerification: return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe })); case SignInStatus.Failure: default: ModelState.AddModelError("", "Intento de inicio de sesión no válido."); return(View(model)); } }
public async Task <ActionResult> Login(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return(View(model)); } var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout : true); switch (result) { case SignInStatus.Success: var user = await UserManager.FindAsync(model.Email, model.Password); if (!user.EmailConfirmed) { TempData["AvisoEmail"] = "Usuário não confirmado, verifique seu e-mail!"; } await SignInAsync(user, model.RememberMe); return(RedirectToLocal(returnUrl)); case SignInStatus.LockedOut: return(View("Lockout")); case SignInStatus.RequiresVerification: return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl })); case SignInStatus.Failure: default: ModelState.AddModelError("", "Login ou Senha incorretos!"); return(View(model)); } }
public async Task <ActionResult> Login(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return(View(model)); } // 這不會計算為帳戶鎖定的登入失敗. // 若要啟用密碼失敗來觸發帳戶鎖定,請變更為 shouldLockout: true var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout : true); switch (result) { case SignInStatus.Success: return(RedirectToLocal(returnUrl)); case SignInStatus.LockedOut: return(View("Lockout")); case SignInStatus.RequiresVerification: return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe })); case SignInStatus.Failure: default: ModelState.AddModelError("", "登入嘗試失敗。"); return(View(model)); } }
public async Task <ActionResult> Login(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return(View(model)); } // This doen't count login failures towards lockout only two factor authentication // To enable password failures to trigger lockout, change to shouldLockout: true var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout : false); switch (result) { case SignInStatus.Success: if (!UserManager.IsEmailConfirmed(UserManager.FindByName(model.Email).Id)) { AuthenticationManager.SignOut(); return(View("DisplayEmail")); } return(RedirectToLocal(returnUrl)); case SignInStatus.LockedOut: return(View("Lockout")); case SignInStatus.RequiresVerification: return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, model.RememberMe })); case SignInStatus.Failure: default: ModelState.AddModelError("", "Invalid login attempt."); return(View(model)); } }
public async Task <ActionResult> Login(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return(View(model)); } // This doen't count login failures towards lockout only two factor authentication // To enable password failures to trigger lockout, change to shouldLockout: true var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout : false); switch (result) { case SignInStatus.Success: //return RedirectToLocalAdmin(returnUrl); return(RedirectToLocal(returnUrl)); case SignInStatus.LockedOut: return(View("Lockout")); case SignInStatus.RequiresVerification: return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl })); case SignInStatus.Failure: default: ModelState.AddModelError("", "Usuario o Clave incorrectos."); return(View(model)); } }
public async Task <ActionResult> Login(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return(View(model)); } ApplicationDbContext db = new ApplicationDbContext(); ApplicationUser user = db.Users.FirstOrDefault(i => i.Email == model.Email); // This doen't count login failures towards lockout only two factor authentication // To enable password failures to trigger lockout, change to shouldLockout: true var result = await SignInManager.PasswordSignInAsync(user.UserName, model.Password, model.RememberMe, shouldLockout : false); switch (result) { case SignInStatus.Success: return(RedirectToLocal(returnUrl)); case SignInStatus.LockedOut: return(View("Lockout")); case SignInStatus.RequiresVerification: return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl })); case SignInStatus.Failure: default: ModelState.AddModelError("", "Invalid login attempt."); return(View(model)); } }
public async Task <ApplicationUser> Authenticate(LoginViewModel loginViewModel) { var res = await _applicationSignInManager.PasswordSignInAsync(loginViewModel.Username, loginViewModel.Password, false, false); if (res.Succeeded) { var applicationUser = await _applicationUserManager.FindByNameAsync(loginViewModel.Username); applicationUser.PasswordHash = null; var tokenHandler = new JwtSecurityTokenHandler(); var key = System.Text.Encoding.ASCII.GetBytes(_appSettings.Secret); var tokenDescriptor = new SecurityTokenDescriptor() { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, applicationUser.Id), new Claim(ClaimTypes.Email, applicationUser.Email) }), Expires = DateTime.UtcNow.AddHours(8), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); applicationUser.Token = tokenHandler.WriteToken(token); return(applicationUser); } else { return(null); } }
public virtual async Task <ActionResult> Login(LoginViewModel model, string returnUrl) { var pmodel = new LoginPage(); if (!ModelState.IsValid) { pmodel.LoginModel = model; pmodel.RegisterModel = new RegisterViewModel(); return(View(pmodel)); } // This doen't count login failures towards lockout only two factor authentication // To enable password failures to trigger lockout, change to shouldLockout: true var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout : false); switch (result) { case SignInStatus.Success: return(RedirectToLocal(returnUrl)); case SignInStatus.LockedOut: return(View("Lockout")); case SignInStatus.RequiresVerification: return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl })); case SignInStatus.Failure: default: ModelState.AddModelError("", "Invalid login attempt."); pmodel.LoginModel = model; pmodel.RegisterModel = new RegisterViewModel(); return(View(pmodel)); } }
public async Task <ActionResult> SignIn(AccountSignInViewModel viewModel) { if (!ModelState.IsValid) { return(View(viewModel)); } // Sign-in the user var result = await _signInManager.PasswordSignInAsync( viewModel.Email, viewModel.Password, viewModel.RememberMe, shouldLockout : false); // Check the result switch (result) { case SignInStatus.Success: return(RedirectToAction("Index", "Entries")); case SignInStatus.Failure: ModelState.AddModelError("", "Invalid login attempt."); return(View(viewModel)); case SignInStatus.LockedOut: case SignInStatus.RequiresVerification: throw new NotImplementedException("Identity feature not implemented."); default: throw new Exception("Unexpected Microsoft.AspNet.Identity.Owin.SignInStatus enum value: " + result); } }
public async Task <ActionResult> Login(LoginViewModel model, string returnUrl) { try { if (string.IsNullOrEmpty(returnUrl)) { returnUrl = "/Dashboard/Home/Index"; } if (!ModelState.IsValid) { return(View(model)); } var user = await UserManager.FindByNameAsync(model.Email); if (user != null) { if (!await UserManager.IsEmailConfirmedAsync(user.Id)) { ModelState.AddModelError("", "Email is not confirmed!"); return(View(model)); } } // This doen't count login failures towards lockout only two factor authentication // To enable password failures to trigger lockout, change to shouldLockout: true var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout : false); switch (result) { case SignInStatus.Success: { //return RedirectToAction("Index", "Admin"); return(RedirectToLocal(returnUrl)); } case SignInStatus.LockedOut: return(View("Lockout")); case SignInStatus.RequiresVerification: { // SetUserPermissions(model.Email); return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl })); } case SignInStatus.Failure: default: ModelState.AddModelError("", "Invalid username/password!"); return(View(model)); } } catch (Exception ex) { return(RedirectToAction("Error")); } }
public async Task <ActionResult> Login(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return(View(model)); } // Require the user to have a confirmed email before they can log on. var user = await UserManager.FindByNameAsync(model.Email); if (user != null) { if (!await UserManager.IsEmailConfirmedAsync(user.Id)) { ViewBag.errorMessage = "You must have a confirmed email to log on."; return(View("Error")); } } // This doen't count login failures towards lockout only two factor authentication // To enable password failures to trigger lockout, change to shouldLockout: true var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout : false); switch (result) { case SignInStatus.Success: if (returnUrl != null) { return(RedirectToLocal(returnUrl)); } return(RedirectToAction("Index", "Home")); case SignInStatus.LockedOut: return(View("Lockout")); case SignInStatus.RequiresVerification: return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl })); case SignInStatus.Failure: default: ModelState.AddModelError("", "Invalid login attempt."); return(View()); } }
public async Task <IHttpActionResult> Login(LoginModel model) { // This doen't count login failures towards lockout only two factor authentication // To enable password failures to trigger lockout, change to shouldLockout: true var result = await signInManager.PasswordSignInAsync(model.Email, model.Password, isPersistent : false, shouldLockout : false); return(Ok(result)); }
public async Task <ActionResult> Login(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return(View(model)); } // The Controller NEEDs the Username to login, so MUST go find the username. var isEmail = Regex.IsMatch(model.Email, @"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" + @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$", RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250)); if (isEmail) { // User is logging in with email, but we need username, so go find username. var db = new ApplicationDbContext(); var user = db.Users.FirstOrDefault(u => u.Email == model.Email); // incase of a bad email. if (user == null) { ModelState.AddModelError("", "Invalid login attempt."); return(View(model)); } // assign Email property to equal Username. model.Email = user.UserName; } //else //{ // // User is logging in with username, don't need to do anything //} // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, change to shouldLockout: true var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout : false); switch (result) { case SignInStatus.Success: return(RedirectToLocal(returnUrl)); case SignInStatus.LockedOut: return(View("Lockout")); case SignInStatus.RequiresVerification: return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe })); case SignInStatus.Failure: default: ModelState.AddModelError("", "Invalid login attempt."); return(View(model)); } }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { _applicationSignInManager = context.OwinContext.GetUserManager <ApplicationSignInManager>(); _applicationUserManager = context.OwinContext.Get <ApplicationUserManager>(); var identity = new ClaimsIdentity(context.Options.AuthenticationType); var dbcontext = ServiceLocator.Current.GetInstance <ApplicationIdentityContext>(); var result = await _applicationSignInManager.PasswordSignInAsync(context.UserName, context.Password, false, true); if (result == SignInStatus.Success) { var user = await _applicationUserManager.FindByNameAsync(context.UserName); if (!user.IsActive) { context.Rejected(); context.SetError("Lỗi đăng nhập", "Tài khoản không tồn tại."); return; } var roles = _applicationUserManager.GetRoles(user.Id); //identity.AddClaim(new Claim(ClaimTypes.Role, String.Join(";", user.Roles.Select(x => x.RoleId).ToArray()))); identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName)); identity.AddClaim(new Claim(ClaimTypes.Sid, user.Id.ToString())); foreach (var role in roles) { identity.AddClaim(new Claim(ClaimTypes.Role, role)); } var data = new Dictionary <string, string> { { "userName", user.UserName }, { "roles", string.Join(",", user.Roles) } }; var properties = new AuthenticationProperties(data); var ticket = new AuthenticationTicket(identity, properties); context.Validated(ticket); } else { context.Rejected(); if (result == SignInStatus.Failure) { context.SetError("Lỗi đăng nhập", "Tài khoản hoặc mật khẩu không chính xác. "); } if (result == SignInStatus.LockedOut) { context.SetError("Khóa tài khoản", "Tài khoản của bạn đã bị khóa, đợi 15 phút để mở lại"); } if (result == SignInStatus.RequiresVerification) { context.SetError("Chưa xác minh tài khoản", "Tài khoản của bạn chưa được xác nhận bởi email hay Admin"); } } }
public async Task <ActionResult> Login(LoginViewModel model, string returnUrl, string invitationCode) { if (!ModelState.IsValid || (ViewBag.Settings.LocalLoginByEmail && string.IsNullOrWhiteSpace(model.Email)) || (!ViewBag.Settings.LocalLoginByEmail && string.IsNullOrWhiteSpace(model.Username))) { //AddErrors(ViewBag.IdentityErrors.InvalidLogin()); AddErrors(new IdentityError() { Description = " Invalid sign-in attempt. Please enter the correct user access credentials." }); return(View(GetLoginViewModel(model, null, returnUrl, invitationCode))); } var rememberMe = ViewBag.Settings.RememberMeEnabled && model.RememberMe; BranchSettingsViewModel userBranchConfiguration = UserBranchConfiguration(model.Username); if (userBranchConfiguration.BranchName != string.Empty && !userBranchConfiguration.IsBranchConfigured) { AddErrors(new IdentityError() { Description = " Your branch has not been configured. Please contact your system administrator to fix this." }); return(View(GetLoginViewModel(model, null, returnUrl, invitationCode))); } setUserBranchCookie(userBranchConfiguration); // This doen't count login failures towards lockout only two factor authentication // To enable password failures to trigger lockout, change to shouldLockout: true SignInStatus result = ViewBag.Settings.LocalLoginByEmail ? await SignInManager.PasswordSignInByEmailAsync(model.Email, model.Password, rememberMe, ViewBag.Settings.TriggerLockoutOnFailedPassword) : await SignInManager.PasswordSignInAsync(model.Username, model.Password, rememberMe, ViewBag.Settings.TriggerLockoutOnFailedPassword); switch (result) { case SignInStatus.Success: return(await RedirectOnPostAuthenticate(returnUrl, invitationCode)); case SignInStatus.LockedOut: AddErrors(ViewBag.IdentityErrors.UserLocked()); return(View(GetLoginViewModel(model, null, returnUrl, invitationCode))); case SignInStatus.RequiresVerification: return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, InvitationCode = invitationCode, RememberMe = rememberMe })); case SignInStatus.Failure: default: AddErrors(new IdentityError() { Description = " Invalid sign-in attempt. Please enter the correct user access credentials." }); //AddErrors(ViewBag.IdentityErrors.InvalidLogin()); return(View(GetLoginViewModel(model, null, returnUrl, invitationCode))); } }
public async Task <IActionResult> Login(LoginInputModel model) { if (ModelState.IsValid) { var result = await _signInManager.PasswordSignInAsync(model.Username, model.Password, model.RememberLogin, lockoutOnFailure : false); if (result.Succeeded) { AuthenticationProperties props = null; // only set explicit expiration here if persistent. // otherwise we reply upon expiration configured in cookie middleware. if (AccountOptions.AllowRememberLogin && model.RememberLogin) { props = new AuthenticationProperties { IsPersistent = true, ExpiresUtc = DateTimeOffset.UtcNow.Add(AccountOptions.RememberMeLoginDuration) }; } ; // issue authentication cookie with subject ID and username var user = await _userManager.FindByNameAsync(model.Username); await HttpContext.SignInAsync(user.Id.ToString(), user.UserName, props); // make sure the returnUrl is still valid, and if yes - redirect back to authorize endpoint if (_interaction.IsValidReturnUrl(model.ReturnUrl)) { return(Redirect(model.ReturnUrl)); } return(Redirect("~/")); } ModelState.AddModelError("", AccountOptions.InvalidCredentialsErrorMessage); } // something went wrong, show form with error var vm = await _accountService.BuildLoginViewModelAsync(model); return(View(vm)); }