public async Task <ActionResult> Login(Models.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.username, model.password, false, shouldLockout : false); switch (result) { case SignInStatus.Success: var user = UserManager.FindByEmail(model.username); HttpCookie aCookie = new HttpCookie("imageUser") { Value = string.IsNullOrEmpty(user.UserProfileInfo.UserImagePerfil) ? user.UserProfileInfo.UserFemale ? "~/Content/rsc/imgs/girl.png" : "~/Content/rsc/imgs/boy.png" : user.UserProfileInfo.UserImagePerfil, Expires = DateTime.Now.AddDays(1) }; Response.Cookies.Add(aCookie); //Session.Add("imageUser", string.IsNullOrEmpty(user.UserProfileInfo.UserImagePerfil) ? user.UserProfileInfo.UserFemale ? "~/Content/rsc/imgs/girl.png" : "~/Content/rsc/imgs/boy.png" : user.UserProfileInfo.UserImagePerfil); return(RedirectToLocal(returnUrl)); case SignInStatus.LockedOut: return(View("Lockout")); case SignInStatus.RequiresVerification: return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, model.remember })); default: ModelState.AddModelError("", "Credenciales inválidas"); return(View(model)); } }
public async Task <IActionResult> Index(Models.LoginViewModel model) { var json = JsonConvert.SerializeObject(model); var Content = new StringContent(json, UnicodeEncoding.UTF8, "application/json"); HttpResponseMessage response = client.PostAsync("Account", Content).Result; //se retornar com sucesso busca os dados if (response.IsSuccessStatusCode) { Retorno retorno = await response.Content.ReadAsAsync <Retorno>(); var claims = new List <Claim>(); claims.Add(new Claim(ClaimTypes.Name, model.Login)); claims.Add(new Claim(ClaimTypes.Role, "admin")); claims.Add(new Claim("AcessToken", string.Format("Bearer {0}", retorno.accessToken))); var identity = new ClaimsIdentity(claims, "ApplicationCookie"); var principal = new ClaimsPrincipal(identity); await HttpContext.SignInAsync("app", principal, new AuthenticationProperties() { IsPersistent = model.IsPersistent }); return(RedirectToAction("Index", "Perguntas")); } return(View()); }
public async Task <ActionResult> Login(Models.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 ActionResult Login(Models.LoginViewModel UserLogin) { User MyUser = (from U in db.Users where U.UserName == UserLogin.User.UserName select U).FirstOrDefault(); if (MyUser != null) { string MyPassword = Mycrypt.HashPassword(UserLogin.User.UserPassword, MyUser.UserSalt); User MyLogIn = (from U in db.Users where U.UserName == UserLogin.User.UserName && U.UserPassword == MyPassword select U).FirstOrDefault(); if (MyLogIn != null) { Session["User"] = UserLogin.User.UserName; return(RedirectToAction("Index", "Admin")); } else { UserLogin.Errmsg = "Wrong username or password!"; return(View(UserLogin)); } } UserLogin.Errmsg = "Wrong username or password!"; return(View(UserLogin)); }
public ActionResult Login(Models.LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return(View(model)); } // 这不会计入到为执行帐户锁定而统计的登录失败次数中 // 若要在多次输入错误密码的情况下触发帐户锁定,请更改为 shouldLockout: true var result = SignInManager.SignIn( model.UserName, model.Password, model.RememberMe, shouldLockout: AppConfig.LockoutEnabled); switch (result) { case SignInStatus.Success: return(RedirectToLocal(returnUrl ?? @"/Home/Main")); 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 ActionResult Login(Models.LoginViewModel loginVM) { if (ModelState.IsValid) { var _admin = _adminService.Find(a => a.Account == loginVM.Account); if (_admin == null) { ModelState.AddModelError("Account", "账号不存在"); } else if (Encryption.Sha256(loginVM.Password) != _admin.Password) { ModelState.AddModelError("Password", "密码不正确"); } else { _admin.LoginTime = System.DateTime.Now; _admin.LoginIp = Request.UserHostAddress; _adminService.Update(_admin); Session.Add("Account", loginVM.Account); Session.Add("Password", _admin.Password); return(RedirectToAction("Index", "Home")); } } return(View(loginVM)); }
public IActionResult Token(Models.LoginViewModel loginModel) { if (ModelState.IsValid) { if (!(loginModel.User == "Dream" && loginModel.Password == "123456")) { return(BadRequest()); } var claims = new Claim[] { new Claim(ClaimTypes.Name, "Dream"), new Claim(ClaimTypes.Role, "admin") }; var key = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(_jwtSettings.SecreKey)); //设置token加密Key var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); //设置加密方式 /* * 加密Token */ var toekn = new JwtSecurityToken( _jwtSettings.Issuser, _jwtSettings.Audience, claims, DateTime.Now, // DateTime.Now.AddMinutes(30), //过期时间 creds ); //最终的Token return(Ok(new { token = new JwtSecurityTokenHandler().WriteToken(toekn) })); } return(BadRequest()); }
public async Task <IActionResult> CreateToken([FromBody] Models.LoginViewModel model) { string[] userRoles = null; switch (model.Password) { case "TextReader": userRoles = new string[] { "TextReader" }; break; case "JsonReader": userRoles = new string[] { "JsonReader" }; break; case "XmlReader": userRoles = new string[] { "XmlReader" }; break; case "Admin": userRoles = new string[] { "Admin" }; break; } try { if (model.Email == "*****@*****.**") { var fakeClaims = new List <Claim>(); fakeClaims.Add(new Claim(ClaimTypes.Name, model.Email)); fakeClaims.Add(new Claim(ClaimTypes.Email, "*****@*****.**")); var userIdentity = new ClaimsIdentity(fakeClaims); userRoles.ToList().ForEach((role) => userIdentity.AddClaim(new Claim(ClaimTypes.Role, role))); var userClaims = fakeClaims; var symmetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JwtSecurityToken:Key"])); var signingCredentials = new SigningCredentials(symmetricSecurityKey, SecurityAlgorithms.HmacSha256); var jwtSecurityToken = new JwtSecurityToken( issuer: configuration["JwtSecurityToken:Issuer"], audience: configuration["JwtSecurityToken:Audience"], claims: userClaims, expires: DateTime.UtcNow.AddMinutes(60), signingCredentials: signingCredentials); return(await Task.FromResult <IActionResult>(Ok(new { token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken), expiration = jwtSecurityToken.ValidTo }))); } return(await Task.FromResult <IActionResult>(Unauthorized())); } catch (Exception ex) { logger.LogError($"error while creating token: {ex}"); return(StatusCode((int)HttpStatusCode.InternalServerError, "error while creating token")); } }
public async Task <ActionResult> Login(Models.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 IHttpActionResult Login(Models.LoginViewModel loginViewModel) { if (ModelState.IsValid) { try { var result = UserManager.Login(loginViewModel.LoginName, loginViewModel.LoginPwd); if (result) { var token = JwtTools.Encode(new Dictionary <string, string>() { { "name", loginViewModel.LoginName } }); return(this.SendData(token)); } else { return(this.ErrorData("账号密码错误")); } } catch (Exception ex) { return(this.ErrorData("出现错误")); } } else { return(this.ErrorData("发生异常")); } }
public async Task <ActionResult> Login(Models.LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return(View(model)); } // 這不會計算為帳戶鎖定的登入失敗 // 若要啟用密碼失敗來觸發帳戶鎖定,請變更為 shouldLockout: true var result = await SignInManager.PasswordSignInAsync(model.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, RememberMe = model.RememberMe })); case SignInStatus.Failure: default: ModelState.AddModelError("", "登入嘗試失試。"); return(View(model)); } }
public LoginView() { InitializeComponent(); BindingContext = new Models.LoginViewModel(); ((Models.LoginViewModel)BindingContext).LoginSuccessfully += LoginView_LoginSuccessfully; }
public ActionResult Login(Models.LoginViewModel model) { if (ModelState.IsValid) { } return(View()); }
public ActionResult Login(string returnUrl) { Models.LoginViewModel model = new Models.LoginViewModel() { ReturnURL = returnUrl }; return(View(model)); }
public IActionResult Login(Models.LoginViewModel modelView) { var user = UserRepository.GetByLogin(modelView.Email, modelView.Passwd); return(View()); }
public ActionResult Login(Models.LoginViewModel user, string JumpUrl) { /*Session["username"] = "******"; * MySqlConnection Conn = new MySqlConnection(strConn); * string strSQL = "select * from users where users.username=@username and users.password=@pwd"; * MySqlCommand cmd = new MySqlCommand(strSQL, Conn); * if (ModelState.IsValid) * { * try * { * cmd.Parameters.AddWithValue("@username", user.username); * cmd.Parameters.AddWithValue("@pwd", user.password); * Conn.Open(); * MySqlDataAdapter da = new MySqlDataAdapter(cmd); * DataTable dt = new DataTable(); * da.Fill(dt); * if (dt.Rows.Count > 0) * { * Response.Redirect("/Home/Index"); * return Content(""); * } * else * { * Session.Clear(); * return Content("No"); * } * } * catch (MySqlException E) * { * Session.Clear(); * return Content("Error"); * } * finally * { * Conn.Close(); * } * } * else * { * Session.Clear(); * return Content("Error"); * }*/ Session["username"] = "******"; if (ModelState.IsValid) { if (user.username == "123" && user.password == "123") { Response.Redirect(JumpUrl); return(Content("")); } } else { Session.Clear(); return(Content("Login Failed!")); } return(Content("Error")); }
public void CreateActiveDirectoryUserCredential(Models.LoginViewModel model) { string username = Utility.GetUserNameFromEmail(model.Email); DboCredential obj = new DboCredential(); obj.Vchr32Name = username; obj.Nvch128Caption = username; // obj.Bin64PasswordHash = string.Empty; obj.BEnabled = true; obj.DtCreated = DateTime.Now; obj.Vchr256CreatedContext = "Creating new Credential Record for Active Directory user"; obj.BintCreatorCredentialId = 1; obj.BintCreatorSpoofOfCredentialId = null; obj.DtModified = DateTime.Now; obj.Vchr256ModifiedContext = string.Empty; obj.BintModifierCredentialId = 1; obj.BintModifierSpoofOfCredentialId = null; obj.BSmokeTest = false; obj.BIsGroup = false; _context.DboCredential.Add(obj); _context.SaveChanges(); var credtype = _context.LkpLocalization.SingleOrDefault(m => m.Vchr128Identifier == "1" && m.NvchMaxText == "Active Directory User" && m.Vchr64LocalizationType == "Title"); DboCredentialAlternate objAl = new DboCredentialAlternate(); objAl.BintPrimaryCredentialId = obj.BintId; objAl.ICredentialTypeId = 1; objAl.Vchr64UserName = model.Email; objAl.DtCreated = DateTime.Now; objAl.Vchr256CreatedContext = "Creating new Credential Alternate Record for Active Directory user"; objAl.BintCreatorCredentialId = 1; objAl.BintCreatorSpoofOfCredentialId = null; objAl.DtModified = DateTime.Now; objAl.Vchr256ModifiedContext = string.Empty; objAl.BintModifierCredentialId = 1; objAl.BintModifierSpoofOfCredentialId = null; objAl.BSmokeTest = false; _context.DboCredentialAlternate.Add(objAl); _context.SaveChanges(); DboCredentialHierarchy dbH = new DboCredentialHierarchy(); dbH.BintParentCredentialId = obj.BintId; dbH.BintChildCredentialId = obj.BintId; dbH.DtCreated = DateTime.Now; dbH.Vchr256CreatedContext = "Creating new Hierarchy for Active Directory user"; dbH.BintCreatorCredentialId = 1; dbH.BintCreatorSpoofOfCredentialId = null; dbH.DtModified = DateTime.Now; dbH.Vchr256ModifiedContext = ""; dbH.BintModifierCredentialId = 1; dbH.BintModifierSpoofOfCredentialId = null; dbH.BSmokeTest = false; _context.DboCredentialHierarchy.Add(dbH); _context.SaveChanges(); }
public override System.Web.Mvc.ActionResult Login(Models.LoginViewModel model, string returnUrl) { var callInfo = new T4MVC_System_Web_Mvc_ActionResult(Area, Name, ActionNames.Login); ModelUnbinderHelpers.AddRouteValues(callInfo.RouteValueDictionary, "model", model); ModelUnbinderHelpers.AddRouteValues(callInfo.RouteValueDictionary, "returnUrl", returnUrl); LoginOverride(callInfo, model, returnUrl); return(callInfo); }
public ActionResult Login(Models.LoginViewModel login, string ReturnUrl = "") { if (!this.ModelState.IsValid) { return(View()); } // Membership.ValidateUser(login.Email, login.Password); //UserBusinessLogic bl = new UserBusinessLogic(); //User userTemp = bl.Validade(user.Email, user.Password); if (!iServiceUser.Validade(login.Email, login.Password)) { ModelState.AddModelError(string.Empty, "Not found user!"); return(View()); } User user = iServiceUser.GetByEmail(login.Email); if (user.IsInRole("Admin") && !ReturnUrl.StartsWith("/Admin")) { ModelState.AddModelError(string.Empty, "Admin can not log in this module!" + Environment.NewLine + "Please go to Admin module and try to log in."); return(View()); } FormsAuthentication.SetAuthCookie(login.Email, false); ModelState.Remove("Password"); this.ViewBag.BGColorMenu = true; if (Url.IsLocalUrl(ReturnUrl)) { if (ReturnUrl.Equals("/Admin/Login/Login")) { return(Redirect("/Admin/Admin/Dashboard")); } return(Redirect(ReturnUrl)); } if (user.IsInRole("Supplier")) { return(RedirectToAction("Dashboard", "Supplier", new { id = user.ID })); } else if (user.IsInRole("Custumer")) { return(RedirectToAction("Dashboard", "Custumer", new { id = user.ID })); } return(RedirectToAction("Index", "Home", new { id = user.ID })); }
public IActionResult Login(Mind.Models.UserModel model = null) { model = model ?? new Mind.Models.UserModel(); var modelView = new Models.LoginViewModel() { Email = model.Email }; return(View(modelView)); }
public IActionResult Login(Models.LoginViewModel model) { var user = userRepository.GetByLogin(model.Email, model.Passwd); if (user == null) { ViewBag.MsgError = "E-mail or password invalid!"; } return(RedirectToAction("Index", "Home")); }
public ActionResult Login(Models.LoginViewModel model) { if (!ModelState.IsValid) { return(View(model)); } FormsAuthentication.RedirectFromLoginPage(model.UserID, false); return(View()); }
public ActionResult Login() { if (Request.IsAuthenticated) { RedirectToAction("Index", "Home"); } else { var model = new Models.LoginViewModel(); return(View(model)); } return(View()); }
public async Task <IActionResult> _Login(Models.LoginViewModel model, string returnUrl = null) { var result = await this._signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, false); if (result.Succeeded) { return(await Task.Run <IActionResult>(() => Json(true))); } else { return(await Task.Run <IActionResult>(() => Json(false))); } }
public IActionResult Login(Models.LoginViewModel loginViewModel) { var result = _accountBll.Login(loginViewModel); if (result.Result.IsSuccess) { return(RedirectToAction("Index", "Home")); } else { ModelState.AddModelError("", result.Result.Message); } return(View()); }
public ActionResult Login(Models.LoginViewModel model) { Random r = new Random(); RefreshToken rt = new RefreshToken(); M_TokenTable mtt = new M_TokenTable(); M_EmployeeLogin obj = new M_EmployeeLogin(); M_Online mol = new M_Online(); string ErrMsg = string.Empty; if (B_EmployeeLogin.Login(ref obj, model.LoginTel, model.Password, ref ErrMsg) != -1) { try { mol.PastTime = (long)DateTime.UtcNow.AddMinutes(30).Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds; mol.LastLogin = DateTime.Now; mol.Admin_BL = 1; mol.Token = r.NextDouble().ToString(); B_Online.Insert(ref mol, ref ErrMsg); rt.iss = "lzfyhgm"; rt.exp = (long)DateTime.UtcNow.AddDays(30).Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds; rt.iat = (long)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;; byte[] key = AES.Md5((rt.exp * r.NextDouble()).ToString(), AES.Md5DataType.t32); byte[] IV = AES.Md5((rt.iat * r.NextDouble()).ToString(), AES.Md5DataType.t16); mtt.AesIV = Convert.ToBase64String(key); mtt.AesKey = Convert.ToBase64String(IV); mtt.Exp = rt.exp; mtt.User_ID = obj.ID; mtt.Sign = RefreshToken.Sign(rt); B_TokenTable.Insert(ref mtt, ref ErrMsg); string refreshtoken = RefreshToken.CreateReftoken(rt, key, IV, obj.ID); string user_agent = HttpContext.Request.Headers.Get("User-Agent"); string token = RefreshToken.CreateToken(obj.ID, user_agent, mol.Token); UseCookie.Add("UserName", model.LoginTel, DateTime.Now.AddMinutes(30)); UseSession.Add("UserName", model.LoginTel); UseCookie.Add("UserID", obj.ID.ToString(), DateTime.Now.AddMinutes(30)); UseSession.Add("UserID", obj.ID.ToString()); UseCookie.Add("token", token, DateTime.Now.AddMinutes(30)); UseSession.Add("token", token); UseCookie.Add("RefreshToken", refreshtoken, DateTime.Now.AddDays(30)); } catch (Exception ex) { Response.Write(ex.Message); return(View()); } return(RedirectToAction("Index")); } Response.Write(ErrMsg); return(View()); }
public ActionResult Login(Models.LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return(View(model)); } if (Security.ValidateCredentials(model.Login, model.Password)) { FormsAuthentication.SetAuthCookie(model.Login, model.RememberMe); return(RedirectToLocal(returnUrl)); } ModelState.AddModelError("", "Invalid username or password"); return(View(model)); }
public ActionResult Login(Models.LoginViewModel loginViewModel, string returnUrl) { if (ModelState.IsValid) { if (authProvider.Authenticate(loginViewModel.UserName, loginViewModel.UserPassword)) { return(Redirect(returnUrl ?? Url.Action("Index", "Admin"))); } else { ModelState.AddModelError("", "Некорректный пароль или имя пользователя"); } } return(View()); }
public async Task <ResultBase <string> > Login(Models.LoginViewModel loginViewModel) { var result = new ResultBase <string> { IsSuccess = false }; using (HttpClient client = new HttpClient()) { var parameters = new Dictionary <string, string> { { "username", loginViewModel.Email }, { "password", loginViewModel.Password } }; var content = new StringContent(JsonConvert.SerializeObject(parameters), Encoding.UTF8, "application/json"); //client.BaseAddress = new Uri(Resources.LoginUrl); client.DefaultRequestHeaders.Accept.Clear(); HttpResponseMessage response = await client.PostAsync(Resources.LoginUrl, content); if (response.IsSuccessStatusCode) { var data = await response.Content.ReadAsStringAsync(); var responseResult = JsonConvert.DeserializeObject <ApiResultBase <string> >(data); if (responseResult.IsSuccess) { string Token = string.Empty; var ResultString = responseResult.Result.ToString(); var StartIndexValue = ResultString.IndexOf("=") + 1; var EndIndexValue = ResultString.IndexOf(", "); if (StartIndexValue != -1 && EndIndexValue != -1) { Token = responseResult.Result.Substring(StartIndexValue, EndIndexValue - StartIndexValue).Trim(); } GetDecodedToken(Token); result.IsSuccess = responseResult.IsSuccess; } else { result.IsSuccess = responseResult.IsSuccess; result.Message = responseResult.Message; } } else { result.Message = "Something went wrong please try again leter"; } } return(result); }
public ActionResult Login(Models.LoginViewModel model) { if (ModelState.IsValid) { if (model.Email == "admin" && model.Password == "123") { return(View()); } else { ModelState.AddModelError("", "帳號密碼有誤"); } return(View(model));; } ModelState.AddModelError("", "資料有誤"); return(View(model));; }