public async Task <IActionResult> GenerateToken([FromBody] ApiLogin model) { if (!ModelState.IsValid) { return(BadRequest("Could not create token")); } var user = await _userManager.FindByEmailAsync(model.Email); if (user != null) { var result = await _signInManager.CheckPasswordSignInAsync(user, model.Password, false); if (result.Succeeded) { var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, user.Email), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"])); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken(_config["Tokens:Issuer"], _config["Tokens:Issuer"], claims, expires: DateTime.Now.AddDays(30), signingCredentials: creds); return(Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token), expiry = token.ValidTo })); } } return(BadRequest("Could not create token")); }
public async Task <IActionResult> Post([FromBody] ApiLogin login) { if (!AppConfig.AllowApiLogin) { return(NotFound()); } var result = await SignInManager.PasswordSignInAsync(login.Email, login.Password, false, true); if (result.Succeeded) { DataService.WriteEvent($"API login successful for {login.Email}."); return(Ok()); } else if (result.IsLockedOut) { DataService.WriteEvent($"API login unsuccessful due to lockout for {login.Email}."); return(Unauthorized("Account is locked.")); } else if (result.RequiresTwoFactor) { DataService.WriteEvent($"API login unsuccessful due to 2FA for {login.Email}."); return(Unauthorized("Account requires two-factor authentication.")); } DataService.WriteEvent($"API login unsuccessful due to bad attempt for {login.Email}."); return(BadRequest()); }
public async Task <IActionResult> Login(ApiLogin login) { if (!ModelState.IsValid) { return(View(login)); } // httpClient? var request = CreateRequestToService(HttpMethod.Post, "/api/account/login", login); var response = await HttpClient.SendAsync(request); if (!response.IsSuccessStatusCode) { if (response.StatusCode == HttpStatusCode.Unauthorized) { ModelState.AddModelError("", "Login or password incorrect."); return(View()); } ModelState.AddModelError("", "Unexpected server error."); return(View()); } var success = PassCookiesToClient(response); if (!success) { ModelState.AddModelError("", "Unexpected server error."); return(View()); } return(RedirectToAction("Index", "Home")); }
public async Task <IActionResult> Login(ApiLogin login) { SignInResult result = await SignInManager.PasswordSignInAsync( login.Username, login.Password, login.RememberMe, false); if (!result.Succeeded) { return(Unauthorized()); // 401 for login failure } return(NoContent()); }
public async Task <ApiLoginResult> Login(ApiLogin value) { // 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(value.Email, value.Password, false, shouldLockout : false); return(new ApiLoginResult { User = User, SignInStatus = result }); }
public async Task <ActionResult> Login(ApiLogin login) { if (!ModelState.IsValid) { return(View(login)); } HttpRequestMessage request = CreateRequestToService(HttpMethod.Post, Configuration["ServiceEndpoints:AccountLogin"], login); HttpResponseMessage response; try { response = await HttpClient.SendAsync(request); } catch { ModelState.AddModelError("", "Unexpected server error"); return(View(login)); } if (!response.IsSuccessStatusCode) { if (response.StatusCode == HttpStatusCode.Unauthorized) { // login failed because bad credentials ModelState.AddModelError("", "Login or password incorrect."); } else { ModelState.AddModelError("", "Unexpected server error"); } return(View(login)); } var success = PassCookiesToClient(response); if (!success) { ModelState.AddModelError("", "Unexpected server error"); return(View(login)); } // login success return(RedirectToAction("Index", "Home")); }
public async Task <HttpResponseMessage> Login([FromBody] ApiLogin login) { if (login == null || !ModelState.IsValid) { return(Request.CreateResponse(HttpStatusCode.BadRequest, "Login Details are not valid")); } var user = await userManager.FindAsync(login.Username, login.Password); if (user == null) { return(Request.CreateResponse(HttpStatusCode.Unauthorized, "Username or Password is invalid")); } string token = jwt.GenerateTokenForUser(user.UserName, user.Id); return(Request.CreateResponse(HttpStatusCode.Accepted, token)); }
public async Task <IActionResult> PostAsync([FromBody] ApiLogin login) { AppUser user = await userManager.FindByNameAsync(login.UserName); if (user != null) { await signInManager.SignOutAsync(); Microsoft.AspNetCore.Identity.SignInResult result = await signInManager.PasswordSignInAsync(user, login.Password, false, false); if (result.Succeeded) { Success respone = new Success(); respone.Key = user.UserKey; return(Ok(respone)); } } Failure failure = new Failure(); failure.failure = "failure"; return(Ok(failure)); }
private async Task<Resposta> Logar(string usuario, string senha) { // using Acr.UserDialogs; Cria as dialog e tost var Dialog = UserDialogs.Instance.Loading("Logando... Aguarde", null, null, true, MaskType.Black); Dialog.Show(); var token = await ApiLogin.Login(usuario, senha); if (token != null) { if (!string.IsNullOrEmpty(token.access_token) && token.Mensagem.Equals("ok")) { AppSettings.Token = token; var resposta = new Resposta(); resposta.Ok = true; //await Navigation.PushModalAsync(new Principal()); // Assim da para voltar Navigation.InsertPageBefore(new Principal(), this); await Navigation.PopAsync(); Dialog.Dispose(); return resposta; } } Dialog.Dispose(); DependencyService.Get<IMessage>().LongAlert("Usuário ou senha inválido, tente novamente!"); return null; }
public IActionResult OnPost() { if (!ModelState.IsValid) { return(Page()); } string key = Consts._CONST_KEY; string tk = ApiLogin.rndTransferKey(); string token = ApiLogin.EncryptString(tk, key); string p0 = Consts._CONST_NUM; string p1 = ApiLogin.EncryptString(Request.Form["loginModel.Username"], key);; string p2 = ApiLogin.EncryptString(Request.Form["loginModel.Password"], key); string p3 = token; var theWebRequest = HttpWebRequest.Create("http://192.168.10.250/ExLogin.aspx/LI"); theWebRequest.Method = "POST"; theWebRequest.ContentType = "application/json; charset=utf-8"; theWebRequest.Headers.Add(HttpRequestHeader.Pragma, "no-cache"); using (var writer = theWebRequest.GetRequestStream()) { string send = null; send = "{\"p0\":\"1\",\"p1\":\"" + p1 + "\",\"p2\":\"" + p2 + "\",\"p3\":\"" + p3 + "\"}"; var data = Encoding.UTF8.GetBytes(send); writer.Write(data, 0, data.Length); } var theWebResponse = (HttpWebResponse)theWebRequest.GetResponse(); var theResponseStream = new StreamReader(theWebResponse.GetResponseStream()); string result = theResponseStream.ReadToEnd(); try { result = "{" + result.Substring(28).Replace("}}", "}"); } catch (Exception e) { ModelState.AddModelError("WrongUP", "نام کاربری یا کلمه عبور اشتباه است"); return(Page()); } var splashInfo = JsonConvert.DeserializeObject <clsExLogin>(result); string backTk = ApiLogin.DecryptString(splashInfo.Status, key); if (tk == ApiLogin.Reverse(backTk)) { splashInfo.id = ApiLogin.DecryptString(splashInfo.id, key); splashInfo.name = ApiLogin.DecryptString(splashInfo.name, key); splashInfo.Status = ApiLogin.DecryptString(splashInfo.Status, key); bool withError = false; if (!_db.TblEmployeeRequestUsers.Where(a => a.FldEmployeeRequestUserId == int.Parse(splashInfo.id)).Any()) { try { TblEmployeeRequestUser t = new TblEmployeeRequestUser(); t.FldEmployeeRequestUserId = Int64.Parse(splashInfo.id); t.FldEmployeeRequestUserUsername = Request.Form["loginModel.Username"]; t.FldEmployeeRequestUserPassword = ApiLogin.sha512(Consts._CONST_SALT + Request.Form["loginModel.Password"] + Consts._CONST_SALT); t.FldEmployeeRequestUserName = splashInfo.name; _db.TblEmployeeRequestUsers.Add(t); _db.SaveChanges(); } catch { withError = true; } } //var user = _db.TblEmployeeRequestUsers.Where(a => a.FldEmployeeRequestUserId == int.Parse(splashInfo.id)).FirstOrDefault(); //if (user != null) //{ // //check name // if (!user.FldEmployeeRequestUserName.Equals(splashInfo.name)) // { // user.FldEmployeeRequestUserName = splashInfo.name; // } // //check pass // if (!user.FldEmployeeRequestUserPassword.Equals(ApiLogin.sha512(Request.Form["loginModel.Password"] + Consts._CONST_SALT))) // { // user.FldEmployeeRequestUserPassword = ApiLogin.sha512(Request.Form["loginModel.Password"] + Consts._CONST_SALT); // } // _db.TblEmployeeRequestUsers.Update(user); // _db.SaveChanges(); // string uid = splashInfo.id; // HttpContext.Session.SetString("uid", uid); // return RedirectToPage("Panel/Index"); //} //else //{ //TblEmployeeRequestUser t = new TblEmployeeRequestUser(); //t.FldEmployeeRequestUserId = Int64.Parse(splashInfo.id); //t.FldEmployeeRequestUserUsername = Request.Form["loginModel.Username"]; //t.FldEmployeeRequestUserPassword = ApiLogin.sha512(Request.Form["loginModel.Password"] + Consts._CONST_SALT); //t.FldEmployeeRequestUserName = splashInfo.name; //_db.TblEmployeeRequestUsers.Add(t); //_db.SaveChanges(); if (!withError) { string uid = splashInfo.id; HttpContext.Session.SetString("uid", uid); return(RedirectToPage("Panel/Index")); } else { ModelState.AddModelError("WrongUP", "در سیستم خطایی رخ داده است ! لطفا در زمان دیگری وارد شوید!"); return(Page()); } //} } else { ModelState.AddModelError("WrongUP", "نام کاربری یا کلمه عبور اشتباه است"); return(Page()); } return(Page()); //var checkUser = _db.TblEmployeeRequestUsers // .Where(a => a.FldEmployeeRequestUserUsername.Equals(loginModel.Username)) // .Where(a => a.FldEmployeeRequestUserPassword.Equals(loginModel.Password)); //if (!checkUser.Any()) //{ // ModelState.AddModelError("WrongUP", "نام کاربری یا کلمه عبور اشتباه است"); // return Page(); //} //string uid = checkUser.FirstOrDefault().FldEmployeeRequestUserId.ToString(); //HttpContext.Session.SetString("uid", uid); //return RedirectToPage("Panel/Index"); }