public ActionResult Login(LoginViewModel model, string returnUrl) { if (ModelState.IsValid) { try { model.PasswordHash = SecurityHelper.CreatePasswordHash(model.Password, ""); UserViewModel authenticatedUser = null; authenticatedUser = _userService.LoginAuthentication(model); if (authenticatedUser != null) { string rememberme = (model.RememberMe) ? "true" : "false"; UserAuthenticate.AddLoginCookie(authenticatedUser.FirstName + " " + authenticatedUser.LastName, authenticatedUser.UserTypeCode, authenticatedUser.Id.ToString(), authenticatedUser.UserTypeName, rememberme); return(RedirectToAction("Index", "Admin")); } else { ModelState.AddModelError("", "User Not Authenticated "); // ViewBag.ErrorMsg = "Please check your username and password! "; } } //catch (CustomException customException) //{ // ModelState.AddModelError("", customException.Message); //} catch (Exception ex) { ModelState.AddModelError("", "Invalid login attempt"); } } return(View(model)); }
public async Task <IActionResult> Token([FromBody] UserAuthenticate model) { if (!ModelState.IsValid) { return (BadRequest( ModelState.Values.SelectMany(v => v.Errors) .Select(modelError => modelError.ErrorMessage) .ToList())); } var user = await _userManager.FindByNameAsync(model.UserName); if (user == null || _passwordHasher.VerifyHashedPassword(user, user.PasswordHash, model.Password) != PasswordVerificationResult.Success) { return(BadRequest()); } var token = await GetJwtSecurityToken(user); return(Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token), expiration = token.ValidTo })); }
/// <summary> /// Log Out /// </summary> /// <returns></returns> public ActionResult LogOut() { HttpContext context = System.Web.HttpContext.Current; UserAuthenticate.Logout(context); return(RedirectToAction("Index", "Account")); }
public bool VerifyUser(UserAuthenticate model) { using (_connection) { try { var query = "SELECT count(*) as user_exist FROM app_user WHERE Username=@username AND Password=@password"; SqlCommand command = new SqlCommand(query, _connection); command.Parameters.Clear(); command.Parameters.AddWithValue("@username", model.Username); command.Parameters.AddWithValue("@password", model.Password); _connection.Open(); if (command.ExecuteScalar().ToString() == "1") { return(true); } return(false); } catch (Exception e) { throw new Exception(e.Message); } finally { _databaseRepository.CloseConnection(); } } }
public UserAuthenticate Authenticate(string email, string passwordHash) { User user = _userService.GetUserByEmailPaswword(email, passwordHash); if (user == null) { return(null); } UserAuthenticate userAuthenticate = new UserAuthenticate(user); var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_appSettings.JwtSecretKey); var tokenDescriptor = new SecurityTokenDescriptor() { Subject = new ClaimsIdentity(new List <Claim>() { new Claim(ClaimTypes.Name, user.Id.ToString()), new Claim(ClaimTypes.Email, user.Email), }), Expires = DateTime.UtcNow.AddHours(4), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); userAuthenticate.Token = tokenHandler.WriteToken(token); return(userAuthenticate); }
public IActionResult Authenticate([FromBody] UserAuthenticate model) { var user = _userService.Authenticate(model.Username, model.Password); if (user == null) { return(BadRequest(new { message = "Username or password is incorrect" })); } var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_appSettings.Secret); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, user.Id.ToString()) }), Expires = DateTime.UtcNow.AddDays(7), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); var tokenString = tokenHandler.WriteToken(token); // return basic user info and authentication token return(Ok(new { Id = user.Id, Username = user.Username, FirstName = user.FirstName, LastName = user.LastName, Token = tokenString })); }
private static IEnumerable <Claim> GetTokenClaims(UserAuthenticate user, IConfiguration Configuration) { return(new List <Claim> { new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(JwtRegisteredClaimNames.Sub, user.Email), new Claim(JwtRegisteredClaimNames.Email, user.Email) }); }
public ActionResult LogOff() { TempData.Keep("result"); //if (UserAuthenticate.IsAuthenticated) // _userService.UserLogOff(UserAuthenticate.LogId); UserAuthenticate.Logout(System.Web.HttpContext.Current); return(RedirectToAction("Index", "Home")); }
private void LogActivity(string strLogCategory, string strLog) { string UserID = (string)Session["UserID"]; string SessionID = (string)Session["SessionID"]; string fName = (string)Session["fName"]; string lName = (string)Session["lName"]; UserAuthenticate.LogActivity(strLogCategory, strLog, UserID, fName, lName, SessionID); }
async public Task <ActionResult <User> > Authenticate([FromBody] UserAuthenticate data) { ICollection <User> users = await _context.Users.Where(u => u.Email.Equals(data.Email) && u.Password.Equals(data.Password)).ToListAsync(); if (users.Count() == 0) { return(NotFound()); } return(Ok(users.First())); }
public ActionResult Login(LoginViewModel model, string returnUrl) { if (ModelState.IsValid) { try { model.PasswordHash = SecurityHelper.CreatePasswordHash(model.Password, ""); string result = ""; UserViewModel authenticatedUser = null; authenticatedUser = _IUserService.LoginAuthentication(model); JavaScriptSerializer js = new JavaScriptSerializer(); string jsonData = js.Serialize(returnUrl); if (!string.IsNullOrEmpty(returnUrl)) { result = JsonConvert.DeserializeObject <string>(returnUrl); } if (authenticatedUser != null) { string rememberme = (model.RememberMe) ? "true" : "false"; UserAuthenticate.AddLoginCookie(authenticatedUser.FirstName + " " + authenticatedUser.LastName, authenticatedUser.UserTypeCode, authenticatedUser.Id.ToString(), authenticatedUser.UserTypeName, rememberme); if (authenticatedUser.UserTypeId == 1) { Session["UserConnected"] = authenticatedUser; return(RedirectToAction("Index", "Admin")); } else { Session["UserConnected"] = authenticatedUser; if (!string.IsNullOrEmpty(result)) { return(RedirectToAction("ServiceRequest", "Home", new { Product = result })); } return(RedirectToAction("Index", "Home")); } } else { ModelState.AddModelError("", "User Not Authenticated "); // ViewBag.ErrorMsg = "Please check your username and password! "; } } catch (CustomException customException) { ModelState.AddModelError("", customException.Message); } catch (Exception ex) { ModelState.AddModelError("", "Invalid login attempt"); } } return(View(model)); }
public IActionResult Authenticate([FromBody] UserAuthenticate request) { var user = _authenticateService.Authenticate(request.Email, request.Password); if (user == null) { return(NotFound()); } return(Ok(user)); }
private async Task <ClaimsIdentity> GetIdentity(UserAuthenticate model) { var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, false, false); if (result.Succeeded) { return(new ClaimsIdentity(new System.Security.Principal.GenericIdentity(model.Email, "Token"), new Claim[] { })); } return(null); }
public IActionResult Login([FromBody] LoginModel model) { UserAuthenticate user = _authService.Authenticate(model.Email, model.PasswordHash); if (user == null) { return(BadRequest("Username or password is incorrect")); } return(Ok(user)); }
public IActionResult Register(UserAuthenticate user) { if (_context.Users.Where(u => u.Username == user.Username).Any()) { return(Unauthorized("An account with that username already exists")); } User newUser = new User(); newUser.Username = user.Username; byte[] salt = new byte[128 / 8]; using (var rng = RandomNumberGenerator.Create()) { rng.GetBytes(salt); } string hashedPass = Convert.ToBase64String( KeyDerivation.Pbkdf2( user.Password, salt, KeyDerivationPrf.HMACSHA512, 10000, 512 / 8)); newUser.Password = hashedPass; newUser.Spice = Convert.ToBase64String(salt); newUser.Type = 'g'; _context.Users.Add(newUser); int count; try { count = _context.SaveChanges(); } catch (System.Exception oops) { Console.Write("\n" + oops.ToString() + "\n\n"); return(StatusCode((int)HttpStatusCode.InternalServerError)); } // if changes occurred it worked, else something went wrong if (count > 0) { return(Ok(newUser)); } return(StatusCode((int)HttpStatusCode.InternalServerError)); }
public bool Login(UserAuthenticate model) { if (model == null) { throw new Exception("User cannot be empty."); } if (string.IsNullOrEmpty(model.Username) || string.IsNullOrEmpty(model.Password)) { throw new Exception("Username or password cannot be empty."); } model.Password = _cryptographyService.Encrypt(model.Password); return(_accountRepository.VerifyUser(model)); }
private async Task <JwtSecurityToken> GetJwtSecurityToken(UserAuthenticate user) { var identity = await GetIdentity(user); if (identity == null) { throw new UnauthorizedAccessException(); } return(new JwtSecurityToken( issuer: Configuration["Tokens:Issuer"], audience: Configuration["Tokens:Issuer"], claims: GetTokenClaims(user, Configuration), expires: DateTime.UtcNow.AddMinutes(10), signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Tokens:Key"])), SecurityAlgorithms.HmacSha256) )); }
public async Task <IActionResult> Authenticate([FromBody] UserAuthenticate userAuthenticate) { try { var user = await _userService.Authenticate(userAuthenticate.UserName, userAuthenticate.Password); if (user == null) { return(BadRequest("Invalid Username/Password")); } // Send Token var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_config.GetValue <string>("AppSettings:Secret")); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, user.Id.ToString()) }), Expires = DateTime.UtcNow.AddDays(7), SigningCredentials = new SigningCredentials( new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha512Signature ) }; var token = tokenHandler.CreateToken(tokenDescriptor); var tokenString = tokenHandler.WriteToken(token); return(Ok( new { Id = user.Id, UserName = user.UserName, FirstName = user.FirstName, LastName = user.LastName, Token = tokenString })); } catch (Exception ex) { return(BadRequest(ex.Message)); } }
public async Task <ActionResult <UserWithTokenDTO> > AuthenticateUser(UserAuthenticate userAuthenticate) { var user = await _context.Users.SingleOrDefaultAsync(u => u.Username.Equals(userAuthenticate.Username)); if (user == null) { return(BadRequest(new { message = "Username is incorrect" })); } if (!_userService.VerifyPassword(user, userAuthenticate.Password)) { return(BadRequest(new { message = "Password is incorrect" })); } UserWithTokenDTO userWithToken = _mapper.Map <UserWithTokenDTO>(user); _userService.Authenticate(userWithToken); return(userWithToken); }
public async Task <IActionResult> Token([FromBody] UserAuthenticate model) { if (!ModelState.IsValid) { return(BadRequest()); } var user = await _userManager.FindByNameAsync(model.Login); if (user == null || new PasswordHasher <User>().VerifyHashedPassword(user, user.PasswordHash, model.Password) != PasswordVerificationResult.Success) { return(BadRequest(new { Message = "Неверный логин или пароль." })); } var token = await GetJwtSecurityToken(user); return(Ok(new JwtSecurityTokenHandler().WriteToken(token))); }
public void Login_WhenCalled_ReturnsOkResult() { //Arrange LoginModel model = new LoginModel() { Email = It.IsAny <string>(), PasswordHash = It.IsAny <string>() }; UserAuthenticate userAuthenticateMock = new UserAuthenticate(); _mockAuthService.Setup(s => s.Authenticate(model.Email, model.PasswordHash)) .Returns(() => userAuthenticateMock); //Act ObjectResult okResult = _authController.Login(model) as ObjectResult; //Assert _mockAuthService.Verify(s => s.Authenticate(It.IsAny <string>(), It.IsAny <string>()), Times.Once); Assert.Equal(StatusCodes.Status200OK, okResult.StatusCode); }
public async Task <ActionResult <string> > Authenticate([FromBody] UserAuthenticate user) { UserViewFull userView = null; var requester = GetRequesterNoFail(); if (user.username != null) { userView = await service.FindByUsernameAsync(user.username, requester); } else if (user.email != null) { userView = await service.FindByEmailAsync(user.email, requester); } //Should this be the same as bad password? eeeehhhh if (userView == null) { return(BadRequest("Must provide a valid username or email!")); } if (!string.IsNullOrWhiteSpace(userView.registrationKey)) //There's a registration code pending { return(BadRequest("You must confirm your email first")); } if (!Verify(userView, user.password)) { return(BadRequest("Password incorrect!")); } TimeSpan?expireOverride = null; //Note: this allows users to create ultimate super long tokens for use like... forever. Until we get //the token expirer set up, this will be SCARY if (user.ExpireSeconds > 0) { expireOverride = TimeSpan.FromSeconds(user.ExpireSeconds); } return(GetToken(userView.id, expireOverride)); }
public async Task TokenTestBadRequest() { var fakeUserManager = new Mock <FakeUserManager>(); var controller = new AccountController(fakeUserManager.Object, _configuration.Object); var model = new UserAuthenticate(); controller.ValidateViewModel(model); var result = await controller.Token(model); Assert.IsInstanceOf <BadRequestResult>(result); result = await controller.Token(new UserAuthenticate() { Login = "******" }); Assert.IsInstanceOf <BadRequestResult>(result); }
public ActionResult ChangePassword(ChangePasswordViewModel model) { try { ViewBag.IsActive = "false"; if (!ModelState.IsValid) { return(View(model)); } model.OldPassword = SecurityHelper.Decrypt(model.OldPassword); if (model.OldPassword == model.NewPassword) { ModelState.AddModelError("", "Current password and new password cannot be same."); return(View(model)); } UserViewModel userModel = _userService.ChangePassword(model); if (!string.IsNullOrWhiteSpace(userModel.Id.ToString())) { UserAuthenticate.Logout(System.Web.HttpContext.Current); UserAuthenticate.AddLoginCookie(userModel.FirstName + " " + userModel.LastName, userModel.UserTypeCode, userModel.Id.ToString(), userModel.UserTypeName, "false"); return(RedirectToAction("Dashboard", "Dashboard", new { data = SecurityHelper.Encrypt(Newtonsoft.Json.JsonConvert.SerializeObject(new Qparams() { LogId = Convert.ToInt64(UserAuthenticate.LogId) })) })); } } catch (CustomException customException) { ModelState.AddModelError("", customException.Message); } catch (Exception ex) { ModelState.AddModelError("", "Due to some technical problem this process cannot be completed. Please try after some time."); } return(View(model)); }
public ActionResult Login(LoginViewModel model, string returnUrl) { if (ModelState.IsValid) { try { model.PasswordHash = SecurityHelper.CreatePasswordHash(model.Password, AppConfig.SaltKey); UserViewModel authenticatedUser = null; authenticatedUser = _userService.LoginAuthentication(model); if (authenticatedUser != null) { string rememberme = (model.RememberMe) ? "true" : "false"; UserAuthenticate.AddLoginCookie(authenticatedUser.FirstName + " " + authenticatedUser.LastName, authenticatedUser.UserTypeCode, authenticatedUser.Id.ToString(), authenticatedUser.UserTypeName, rememberme); return(RedirectToAction("Dashboard", "Dashboard", new { data = SecurityHelper.Encrypt(Newtonsoft.Json.JsonConvert.SerializeObject(new Qparams() { LogId = Convert.ToInt64(authenticatedUser.Id) })) })); } else { ModelState.AddModelError("", "User Not Authenticated "); // ViewBag.ErrorMsg = "Please check your username and password! "; } } catch (CustomException customException) { ModelState.AddModelError("", customException.Message); } catch (Exception ex) { ModelState.AddModelError("", "Invalid login attempt"); } } return(View(model)); }
public async Task <IActionResult> Login([FromBody] UserAuthenticate model) { if (!ModelState.IsValid) { return (BadRequest( ModelState.Values.SelectMany(v => v.Errors) .Select(modelError => modelError.ErrorMessage) .ToList())); } var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, false, false); if (!result.Succeeded) { return(BadRequest( ModelState.Values.SelectMany(v => v.Errors) .Select(modelError => modelError.ErrorMessage) .ToList())); } var user = await _userManager.FindByNameAsync(model.UserName); var token = await GetJwtSecurityToken(user); var returnToken = new JwtSecurityTokenHandler().WriteToken(token); return(Ok(new { fullName = user.FullName, email = user.Email, token = returnToken, expiration = token.ValidTo })); }
public IActionResult Login(UserAuthenticate user) { User foundUser = _context.Users.Where(p => p.Username == user.Username).Single(); if (foundUser == null) { return(BadRequest(new { message = "Incorrect Username" })); } string hashed = Convert.ToBase64String( KeyDerivation.Pbkdf2( user.Password, Convert.FromBase64String(foundUser.Spice), KeyDerivationPrf.HMACSHA512, 10000, 512 / 8)); if (foundUser.Password != hashed) { return(BadRequest(new { message = "Incorrect Password" })); } // Create JWT var secretKey = new SymmetricSecurityKey( Encoding.UTF8.GetBytes(Configuration.GetValue <string>("SecretKey"))); var signingCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256); JwtSecurityToken tokenOptions; if (foundUser.Type == 'a') { tokenOptions = new JwtSecurityToken( issuer: Configuration.GetValue <string>("ValidIssuer"), audience: Configuration.GetValue <string>("ValidAudience"), claims: new List <Claim>() { new Claim("Username", foundUser.Username), new Claim("Account Type", AccountType.Admin) }, expires: DateTime.Now.AddYears(1), signingCredentials: signingCredentials ); } else { tokenOptions = new JwtSecurityToken( issuer: Configuration.GetValue <string>("ValidIssuer"), audience: Configuration.GetValue <string>("ValidAudience"), claims: new List <Claim>() { new Claim("Username", foundUser.Username), new Claim("Account Type", AccountType.General) }, expires: DateTime.Now.AddYears(1), signingCredentials: signingCredentials ); } // Return stringified JWT to client var tokenString = new JwtSecurityTokenHandler().WriteToken(tokenOptions); return(Ok(new { Id = foundUser.Id, Username = foundUser.Username, Token = tokenString })); }
public RegistrationController(IDAFactory daFactory, JWTFactory jwt, ApiServerConfiguration config) : base("/userapi/registration") { JWTTokenAuthentication.Enable(this, jwt); DAFactory = daFactory; After.AddItemToEndOfPipeline(x => { x.Response.WithHeader("Access-Control-Allow-Origin", "*"); }); //Create a new user Post["/"] = x => { var user = this.Bind <RegistrationModel>(); var tryIP = Request.Headers["X-Forwarded-For"].FirstOrDefault(); if (tryIP != null) { tryIP = tryIP.Substring(tryIP.LastIndexOf(',') + 1).Trim(); } var ip = tryIP ?? Request.UserHostAddress; user.username = user.username ?? ""; user.username = user.username.ToLowerInvariant(); user.email = user.email ?? ""; user.key = user.key ?? ""; string failReason = null; if (user.username.Length < 3) { failReason = "user_short"; } else if (user.username.Length > 24) { failReason = "user_long"; } else if (!USERNAME_VALIDATION.IsMatch(user.username ?? "")) { failReason = "user_invalid"; } else if ((user.password?.Length ?? 0) == 0) { failReason = "pass_required"; } if (failReason != null) { return(Response.AsJson(new RegistrationError() { error = "bad_request", error_description = failReason })); } bool isAdmin = false; if (config.Regkey != null && config.Regkey != user.key) { return(Response.AsJson(new RegistrationError() { error = "key_wrong", error_description = failReason })); } var passhash = PasswordHasher.Hash(user.password); using (var da = daFactory.Get) { //has this ip been banned? var ban = da.Bans.GetByIP(ip); if (ban != null) { return(Response.AsJson(new RegistrationError() { error = "registration_failed", error_description = "ip_banned" })); } //has this user registered a new account too soon after their last? var now = Epoch.Now; var prev = da.Users.GetByRegisterIP(ip); if (now - (prev.FirstOrDefault()?.register_date ?? 0) < REGISTER_THROTTLE_SECS) { //cannot create a new account this soon. return(Response.AsJson(new RegistrationError() { error = "registration_failed", error_description = "registrations_too_frequent" })); } //TODO: is this ip banned? var userModel = new User { username = user.username, email = user.email, is_admin = isAdmin, is_moderator = isAdmin, user_state = UserState.valid, register_date = now, is_banned = false, register_ip = ip, last_ip = ip }; var authSettings = new UserAuthenticate { scheme_class = passhash.scheme, data = passhash.data }; try { var userId = da.Users.Create(userModel); authSettings.user_id = userId; da.Users.CreateAuth(authSettings); userModel = da.Users.GetById(userId); if (userModel == null) { throw new Exception("Unable to find user"); } return(Response.AsJson(userModel)); } catch (Exception) { return(Response.AsJson(new RegistrationError() { error = "registration_failed", error_description = "user_exists" })); } } }; }
public HttpResponseMessage Post(HttpRequestMessage request, [FromBody] RegistrationModel user) { var api = Api.INSTANCE; var ip = ApiUtils.GetIP(Request); user.username = user.username ?? ""; user.username = user.username.ToLowerInvariant(); user.email = user.email ?? ""; user.key = user.key ?? ""; string failReason = null; if (user.username.Length < 3) { failReason = "user_short"; } else if (user.username.Length > 24) { failReason = "user_long"; } else if (!USERNAME_VALIDATION.IsMatch(user.username ?? "")) { failReason = "user_invalid"; } else if ((user.password?.Length ?? 0) == 0) { failReason = "pass_required"; } if (failReason != null) { return(ApiResponse.Json(HttpStatusCode.OK, new RegistrationError() { error = "bad_request", error_description = failReason })); } bool isAdmin = false; if (!string.IsNullOrEmpty(api.Config.Regkey) && api.Config.Regkey != user.key) { return(ApiResponse.Json(HttpStatusCode.OK, new RegistrationError() { error = "key_wrong", error_description = failReason })); } var passhash = PasswordHasher.Hash(user.password); using (var da = api.DAFactory.Get()) { //has this ip been banned? var ban = da.Bans.GetByIP(ip); if (ban != null) { return(ApiResponse.Json(HttpStatusCode.OK, new RegistrationError() { error = "registration_failed", error_description = "ip_banned" })); } //has this user registered a new account too soon after their last? var now = Epoch.Now; var prev = da.Users.GetByRegisterIP(ip); if (now - (prev.FirstOrDefault()?.register_date ?? 0) < REGISTER_THROTTLE_SECS) { //cannot create a new account this soon. return(ApiResponse.Json(HttpStatusCode.OK, new RegistrationError() { error = "registration_failed", error_description = "registrations_too_frequent" })); } //TODO: is this ip banned? var userModel = new User(); userModel.username = user.username; userModel.email = user.email; userModel.is_admin = isAdmin; userModel.is_moderator = isAdmin; userModel.user_state = UserState.valid; userModel.register_date = now; userModel.is_banned = false; userModel.register_ip = ip; userModel.last_ip = ip; var authSettings = new UserAuthenticate(); authSettings.scheme_class = passhash.scheme; authSettings.data = passhash.data; try { var userId = da.Users.Create(userModel); authSettings.user_id = userId; da.Users.CreateAuth(authSettings); userModel = da.Users.GetById(userId); if (userModel == null) { throw new Exception("Unable to find user"); } return(ApiResponse.Json(HttpStatusCode.OK, userModel)); } catch (Exception) { return(ApiResponse.Json(HttpStatusCode.OK, new RegistrationError() { error = "registration_failed", error_description = "user_exists" })); } } }
public string PostData([FromBody] UserAuthenticate user) { return(string.Empty); }