/// <summary> /// 進行AD帳號驗證 使用FormsAuthenticationTicket驗證 /// </summary> /// <param name="logonModel"></param> /// <returns></returns> //private string ValidADAccountByFormsAuthenticationTicket(LogonViewModel logonModel) //{ // #region AD驗證 // var now = DateTime.Now; // string domainName = logonModel.DomainName; // string adValidMsg = string.Empty; // string adPath = "LDAP://" + domainName; // LdapAuthentication adAuth = new LdapAuthentication(adPath); // try // { // if (true == adAuth.IsAuthenticated(domainName, logonModel.Account, logonModel.Password)) // { // string groups = adAuth.GetGroups(); // //取出該會員的角色 // //string roles = string.Join(",", user.SystemRoles.Select(x => x.Name).ToArray()); // var ticket = new FormsAuthenticationTicket( // version: 1, // name: logonModel.Name, // issueDate: now, // expiration: now.AddMinutes(30), // isPersistent: logonModel.Remember, // userData: logonModel.Account, // cookiePath: FormsAuthentication.FormsCookiePath); // //表單門票加密 // var encryptedTicket = FormsAuthentication.Encrypt(ticket); // //放入cookie // var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); // Response.Cookies.Add(cookie); // } // else // { // adValidMsg = "請輸入正確的帳號或密碼!"; // } // } // catch (Exception ex) // { // adValidMsg = "請輸入正確的帳號或密碼!"; // } // #endregion AD驗證 // return adValidMsg; //} /// <summary> /// 進行AD帳號驗證 /// </summary> /// <param name="logonModel"></param> /// <returns></returns> private string ValidADAccountByCustom(LogonViewModel logonModel) { #region AD驗證 var now = DateTime.Now; string domainName = logonModel.DomainName; string adValidMsg = string.Empty; string adPath = "LDAP://" + domainName; LdapAuthentication adAuth = new LdapAuthentication(adPath); try { if (!adAuth.IsAuthenticated(domainName, logonModel.Account, logonModel.Password)) { adValidMsg = "請輸入正確的帳號或密碼!"; } } catch (Exception) { adValidMsg = "請輸入正確的帳號或密碼!"; } #endregion AD驗證 return(adValidMsg); }
public ActionResult Login(LogonViewModel pageData) { if (pageData.Account == "*****@*****.**" && pageData.Password == "123456") { //pageData.ReturnCode = 0; pageData.Message = $"您使用{pageData.Account}登入成功。"; TempData["LoginMsg"] = $"您使用{pageData.Account}登入成功。"; Session.RemoveAll(); FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, pageData.Account, DateTime.Now, DateTime.Now.AddMinutes(1), false, pageData.Account, FormsAuthentication.FormsCookiePath); string encTicket = FormsAuthentication.Encrypt(ticket); Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket)); return(RedirectToAction("Index", "Home")); } else { //pageData.ReturnCode = -1; pageData.Message = "登入失敗!"; } return(View(pageData)); }
public async Task <IActionResult> Login(LogonViewModel login) { var usuario = await _dbuser.Login(login.Info, login.Senha); if (usuario != null) { var claims = new[] { new Claim(JwtRegisteredClaimNames.Email, usuario.Email), new Claim(JwtRegisteredClaimNames.Jti, usuario.Id.ToString()), }; var chave = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes("keyteste019104934")); var credencial = new SigningCredentials(chave, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken( issuer: "WTower.WebApi", audience: "WTower.WebApi", claims: claims, expires: DateTime.Now.AddMinutes(30), signingCredentials: credencial ); return(Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) })); } return(NotFound(new { msgerr = "Não foi possível fazer login, verifique as suas credenciais e tente novamente" })); }
public LogonView() { InitializeComponent(); BindingContext = new LogonViewModel(Navigation); NavigationPage.SetHasNavigationBar(this, false); NavigationPage.SetHasBackButton(this, false); }
public ActionResult LogOn(LogonModel model, string returnUrl) { IAccountContract AccountContract = Actor.Public.AsAccountManager(); if (AccountContract.ValidateUser(model.UserName, AccountContract.EncryptPassword(model.Password))) { BzureUser user = AccountContract.GetUserByName(model.UserName); user.SignIn(model.RememberMe); if (Url.IsLocalUrl(returnUrl)) { return(Redirect(returnUrl)); } else { return(Redirect("/")); } } else { LogonViewModel ViewModel = new LogonViewModel() { Title = "用户登录", Message = "用户名或密码不正确", MasterViewModel = this.MasterViewModel }; return(this.Result(ViewModel)); } }
public ActionResult Logon(LogonViewModel model) { var memberAccount = db.SystemUsers.FirstOrDefault(x => x.Account == model.Account); //驗證身份 //CooKie if (ModelState.IsValid) { if (memberAccount != null && memberAccount.Password == model.Password) { FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, model.Account, DateTime.Now, DateTime.Now.AddMinutes(30), model.Remember, //將管理者登入的Cookie設定成Session Cookie memberAccount.ID.ToString(), //role FormsAuthentication.FormsCookiePath); //取得form表單路徑 //建立加密的票 string encTicket = FormsAuthentication.Encrypt(ticket); //將票加入Cookie HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket); if (model.Remember == true) { cookie.Expires = DateTime.Now.AddYears(1); } Response.Cookies.Add(cookie); return(RedirectToAction("Index", "Categories")); } ModelState.AddModelError("LogOnError", "請輸入正確的帳號或密碼"); } return(View()); }
public ActionResult Logon(LogonViewModel pageData) { if (pageData.Email.Contains("skilltree") || pageData.Email.Contains("demo") || pageData.Email.Contains("twMVC")) { if (pageData.Email.Contains("skilltree")) { ModelState.AddModelError("Email", "帳號不得包含skilltree的字串"); } else if (pageData.Email.Contains("demo")) { ModelState.AddModelError("Email", "帳號不得包含demo的字串"); } else if (pageData.Email.Contains("twMVC")) { ModelState.AddModelError("Email", "帳號不得包含twMVC的字串"); } ViewData["alert"] = "alert-danger"; } else { pageData.Message = $"您使用{pageData.Email}登入成功。"; ViewData["alert"] = "alert-success"; } return(View(pageData)); }
public async Task <ActionResult <TokenResponseViewModel> > Post([FromBody] LogonViewModel credentials) { if (!ModelState.IsValid) { return(BadRequest(AuthenticationErrorViewModel.Init(ModelState))); } // user name used at logon is "email" var identity = await GetClaimsIdentity(credentials.UserName, credentials.Password); if (identity == null) { return(BadRequest(AuthenticationErrorViewModel.Init(Errors.AddErrorToModelState("login_failure", "User not known.", ModelState)))); } var user = new UserViewModel { UserName = identity.Name, Id = identity.Claims.Single(c => c.Type == "id").Value }; // log user immediately in var result = await _signin.CheckPasswordSignInAsync(user, credentials.Password, true); if (!result.Succeeded) { return(BadRequest(AuthenticationErrorViewModel.Init(Errors.AddErrorToModelState("login_failure", "Invalid username or password.", ModelState)))); } // Serialize and return the response var response = new TokenResponseViewModel { Id = identity.Claims.Single(c => c.Type == "id").Value, AuthToken = await _jwtFactory.GenerateEncodedToken(credentials.UserName, identity), ExpiresIn = (int)_jwtOptions.ValidFor.TotalSeconds }; return(response); }
private void LogonRemote(LogonViewModel viewModel) { var intAccMngr = new AccountManager() { Adapter = Adapters.AdapterType.Controller }; var extAccMngr = new AccountManager() { Adapter = Adapters.AdapterType.Service, BaseUri = viewModel.IdentityUrl }; try { var externLogin = AsyncHelper.RunSync(() => extAccMngr.LogonAsync(viewModel.Email, viewModel.Password)); var internLogin = AsyncHelper.RunSync(() => intAccMngr.LogonAsync(externLogin.JsonWebToken)); var loginSession = new LoginSession(); loginSession.CopyProperties(internLogin); SessionWrapper.LoginSession = loginSession; AsyncHelper.RunSync(() => extAccMngr.LogoutAsync(externLogin.SessionToken)); } catch (Exception ex) { throw ex; } }
private async Task ExecuteLogonRemoteAsync(LogonViewModel viewModel) { var intAccMngr = new AccountManager() { Adapter = Adapters.AdapterType.Controller }; var extAccMngr = new AccountManager() { Adapter = Adapters.AdapterType.Service, BaseUri = viewModel.IdentityUrl }; try { var externLogin = await extAccMngr.LogonAsync(viewModel.Email, viewModel.Password).ConfigureAwait(false); var internLogin = await intAccMngr.LogonAsync(externLogin.JsonWebToken).ConfigureAwait(false); var loginSession = new LoginSession(); loginSession.CopyProperties(internLogin); SessionWrapper.LoginSession = loginSession; await extAccMngr.LogoutAsync(externLogin.SessionToken).ConfigureAwait(false); } catch (Exception ex) { throw ex; } }
public async Task <IActionResult> LogonRemoteAsync(LogonViewModel viewModel) { if (ModelState.IsValid == false) { return(View(viewModel)); } bool handled = false; var action = "Index"; var controller = "Home"; BeforeDoLogonRemote(viewModel, ref handled); if (handled == false) { try { await ExecuteLogonRemoteAsync(viewModel).ConfigureAwait(false); } catch (Exception ex) { viewModel.ActionError = ex.Message; return(View(viewModel)); } } AfterDoLogonRemote(viewModel, ref action, ref controller); if (viewModel.ReturnUrl.HasContent()) { return(Redirect(viewModel.ReturnUrl)); } return(RedirectToAction(action, controller)); }
private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e) { LogonViewModel vm = DataContext as LogonViewModel; vm.Logon = LoginBox.Text; vm.BaseURL = BaseURL.Text; vm.LogonCommand.Execute(passBox); }
public ActionResult Login(LogonViewModel pageData) { if (pageData.Account == "*****@*****.**" && pageData.Password == "tree") { pageData.Message = $"您使用{pageData.Account}登入成功。"; } return(View(pageData)); }
private bool ShowLogonForm() { _shellModel.IsAuthorizationFailed = true; var logonViewModel = new LogonViewModel("1"); WindowManager.ShowDialog(logonViewModel); _shellModel.IsAuthorizationFailed = !logonViewModel.Result; return(logonViewModel.Result); }
protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); LogonViewModel login = new LogonViewModel(); webViewControl.Source = new Uri(string.Format("https://oauth.yandex.ru/authorize?response_type=token&client_id=" + "c087f4071220480dabba7a35f6172681" + "&login_hint={0}&force_confirm=yes", login.Email, login.Password)); }
public ActionResult Logon(LogonViewModel logonViewModel) { if (ModelState.IsValid && WebSecurity.Login(logonViewModel.UserName, logonViewModel.Password, false)) { return(RedirectToAction("Index", "Home")); } ModelState.AddModelError("UserNotAuthenticated", "User is not identified"); return(View(logonViewModel)); }
public void SignIn(LogonViewModel user) { AccountModule module = new AccountModule(); Employee userInfo = module.GetPrototypeEmployeeByAccountID(user.Account, this.PortalDB); if (userInfo == null) { throw new Exception("請輸入正確帳號或密碼"); } m_user = this.CreateUser(userInfo); Context.Session["UserInfo"] = m_user; }
public ActionResult LogOn(LogonViewModel model) { if (ModelState.IsValid) { _userEventHandler.LoggingIn(model.UserNameOrEmail, model.Password); var user = ValidateLogOn(model.UserNameOrEmail, model.Password); _authenticationService.SignIn(user, model.RememberMe); _userEventHandler.LoggedIn(user); return(this.RedirectLocal(model.ReturnUrl)); } return(View("Logon", "Layout2")); }
public ActionResult Logon(LogonViewModel pageData) { if (pageData.Account != null && pageData.Password != null) { pageData.Account = $"您使用{pageData.Account}登入成功。"; return(RedirectToAction("Logoned"));//導入登入畫面中 } else { pageData.Account = $"您使用{pageData.Account}登入失敗。"; } return(View(pageData)); }
public async Task <IActionResult> Logon(LogonViewModel model) { if (ModelState.IsValid) { // Authenticate first var authenticated = _externalAuthenticationProvider.Authenticate(model.UserName, model.Password); if (authenticated) { var user = await _memberService.GetUserByUsernameAsync(model.UserName); if (user != null) { if (string.IsNullOrWhiteSpace(user.Name) || string.IsNullOrWhiteSpace(user.EMail)) { // Not Registered properly await _signinManager.SignInAsync(UserState.FromUser(user)); return(RedirectToAction("Index", "Member")); } // Registered properly await _signinManager.SignInAsync(UserState.FromUser(user)); return(RedirectToAction("Index", "Home")); } var result = await _memberService.RegisterNewUserAsync(model.UserName); if (result == 1) { user = _memberService.GetUserByUsernameAsync(model.UserName).GetAwaiter().GetResult(); await _signinManager.SignInAsync(UserState.FromUser(user)); return(RedirectToAction("Index", "Member")); } // Could't register, might try again. ModelState.AddModelError(Constants.ModelStateCustomErrorKey, RegisteringNewUserFailureMessage); } else { _logger.Warn($"Authentication failure for user {model.UserName}!"); ModelState.AddModelError(Constants.ModelStateCustomErrorKey, InvalidLogonMessage); } } model = new LogonViewModel { UserName = model.UserName }; return(View(model)); }
public ActionResult Logon(LogonViewModel model) { var apiUserController = DependencyResolver.Current.GetService <Api.UserController>(); if (apiUserController.Login(model.Name, model.Password, model.UserTimeOffset).StatusCode == System.Net.HttpStatusCode.OK) { return(RedirectToAction("Index")); } else { ModelState.AddModelError("*", "Somethig went wrong"); return(View(model)); } }
public void Model_Logon_InvalidModel_Returns_ModelStateError() { var model = new LogonViewModel { UserName = "", Password = "" }; var context = new ValidationContext(model, null, null); var validationResults = new List <ValidationResult>(); var valid = Validator.TryValidateObject(model, context, validationResults, true); Assert.False(valid); Assert.AreEqual(2, validationResults.FindAll(i => i.ErrorMessage.Length > 0).Count); }
public ActionResult Logon(LogonViewModel model, string returnUrl = "") { if (ModelState.IsValid) { var user = _userService.FindUserBy(model.UserName, model.Password); if (user != null) { SessionProvider.Login(user); return(Json(new { Success = true })); } return(Json(new { Success = false, Error = "Login failed" })); } return(Json(new { Success = false, Error = "Invalid or empty username/password" })); }
public ActionResult Logn(LogonViewModel padeDate) { if (padeDate.Account == "skill" && padeDate.Password == "tree") { padeDate.Message = $"您使用{padeDate.Account}登入成功。"; } else { padeDate.Message = $"您使用{padeDate.Account}登入失敗。"; } return(View(padeDate)); }
public ActionResult Create(LogonViewModel loginUser) { Logger.Info(string.Format("User Name: {0}; Password {1}", loginUser.Email, loginUser.Password)); if (ModelState.IsValid) { User entityUser = _userService.Logon(loginUser.Email, loginUser.Password); if (entityUser != null) { CreateCookie(entityUser.Name); return Json(new UserViewModel(entityUser)); } Logger.Info("User failed to login."); } return Json(new UserViewModel()); }
public async Task Controller_Logon_ValidAndNotRegisteredUser_Returns_RedirectToActionMemberIndex() { var model = new LogonViewModel { UserName = "******", Password = "******" }; var result = await _controllerWitNullUserState.Logon(model); Assert.NotNull(result); Assert.AreEqual(typeof(RedirectToActionResult), result.GetType()); var redirectToActionResult = (RedirectToActionResult)result; Assert.AreEqual("Member", redirectToActionResult.ControllerName); Assert.AreEqual("Index", redirectToActionResult.ActionName); }
public ActionResult Logon(LogonViewModel pageData) { if (pageData.Account == "skill" && pageData.PassWord == "tree") { pageData.Message = $"成功。"; ViewData["class_name"] = "warning"; } else { pageData.Message = $"失敗。"; ViewData["class_name"] = "danger"; } return(View(pageData)); }
public async Task Controller_Logon_InvalidUser_Returns_ModelStateError() { var model = new LogonViewModel { UserName = "******", Password = "******" }; var result = await _controllerWitNullUserState.Logon(model); Assert.NotNull(result); Assert.AreEqual(typeof(ViewResult), result.GetType()); var viewResult = (ViewResult)result; Assert.NotNull(viewResult.ViewData.ModelState[Constants.ModelStateCustomErrorKey].Errors); Assert.AreEqual(1, viewResult.ViewData.ModelState[Constants.ModelStateCustomErrorKey].Errors.Count); Assert.True(viewResult.ViewData.ModelState[Constants.ModelStateCustomErrorKey].Errors.Any(p => p.ErrorMessage.Equals(MemberController.InvalidLogonMessage))); }
public async Task <IActionResult> Login(LogonViewModel model) { if (ModelState.IsValid) { var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, true, lockoutOnFailure : false); if (result.Succeeded) { return(RedirectToAction("Index", "Home")); } else { ModelState.AddModelError(string.Empty, "Nom ou mot de passe invalide"); return(View(model)); } } return(View()); }
public ActionResult Login(LogonViewModel model) { var result = UserService.Authenticate(model.Email, model.Password); if (result.IsAuthenticated) { Response.SetUserPermissions(result.User.UserRoles.SelectMany(r => r.WebPermissions).Select(wp => wp.Name)); Response.SetAuth(result.User.Email); return(RedirectToAction("Index", "Home")); } else { return(RedirectToAction("Logon", "Account", new LogonViewModel { Email = model.Email, Message = result.Message })); } }
public async Task <IActionResult> Logon(LogonViewModel logUser) { if (ModelState.IsValid) { Microsoft.AspNetCore.Identity.SignInResult res = await _signInManager.PasswordSignInAsync(logUser.UserName, logUser.Password, false, false); if (res.Succeeded) { return(RedirectToAction("Index", "Home")); } if (res.IsLockedOut) { ModelState.AddModelError("Locked out!", "Too many attemts"); } } return(View(logUser)); }
public static Uri Run(MainWindow owner) { var dialog = new LogonDialog(); var model = new LogonModel(); var viewModel = new LogonViewModel(model); dialog.Owner = owner; dialog.DataContext = viewModel; dialog.OnLoadCompleted += (s, e) => { model.Uri = e.Item; dialog.Close(); }; dialog.ShowDialog(); return model.Uri; }