public void CreateAccessToken_ReturnsAccessToken_WhenTokenCreated() { //Arrange mockPasswordHasher = new Mock <IPasswordHasher>(); mockPasswordHasher.Setup(a => a.HashPassword(It.IsAny <string>())).Returns("test"); TokenHandler tokenHandler = new TokenHandler(GetFakeConfigs(), new SigningConfigurations(), mockPasswordHasher.Object); User user = new User { Email = "[email protected]", Password = "******", UserRoles = new List <UserRole> { new UserRole() { Role = new Role() { Name = "Common" } } } }; //Act var result = tokenHandler.CreateAccessToken(user); //Assert var accessToken = Assert.IsAssignableFrom <AccessToken>(result); }
public ActionResult <DtoUser> Post(Refresh refresh) { try { var redisManager = new RedisCacheManager(); _logger.LogInformation("refresh istegi geldi..."); var tokens = new JwtSecurityToken(jwtEncodedString: refresh.authToken); var userId = tokens.Claims.First(c => c.Type == "unique_name").Value; var session = redisManager.Get(userId); if (session == null) { return(BadRequest()); } if (!refresh.authToken.Equals(session)) { return(Forbid()); } var user = _userContext.users.FirstOrDefault(u => u.id.Equals(long.Parse(userId)) && u.refreshtoken.Equals(refresh.refreshToken)); if (user == null) { return(Forbid()); } if (user.refreshtokenexpirationdate > DateTime.Now) { TokenHandler tokenHandler = new TokenHandler(); Token token = tokenHandler.CreateAccessToken(user.id); user.refreshtoken = token.RefreshToken; _userContext.SaveChanges(); redisManager.Remove(user.id.ToString()); redisManager.Set(user.id.ToString(), token.AccessToken, 300); return(Ok(new DtoUser { authToken = token.AccessToken, name = user.name, surname = user.surname, refreshToken = token.RefreshToken })); } return(Forbid()); } catch (Exception e) { _logger.LogError(e.ToString()); return(BadRequest()); } }
public void TakeRefreshToken_ReturnsRefreshTokenAfterRemovingIt_WhenTokenExists() { //Arrange mockPasswordHasher = new Mock <IPasswordHasher>(); mockPasswordHasher.Setup(s => s.HashPassword(It.IsAny <string>())).Returns("test"); TokenHandler tokenHandler = new TokenHandler(GetFakeConfigs(), new SigningConfigurations(), mockPasswordHasher.Object); User user = new User { Email = "[email protected]", Password = "******", UserRoles = new List <UserRole> { new UserRole() { Role = new Role() { Name = "Common" } } } }; var accessToken = tokenHandler.CreateAccessToken(user); //Act var result = tokenHandler.TakeRefreshToken("test"); //Assert var refreshToken = Assert.IsAssignableFrom <RefreshToken>(result); Assert.NotNull(refreshToken); Assert.Equal(refreshToken, accessToken.RefreshToken); }
public JsonResult RefreshToken() { var userRefreshToken = HttpContext.User.Claims.Where(c => c.Type == ClaimTypes.NameIdentifier) .Select(c => c.Value).SingleOrDefault(); var userLogin = UserLoginRepo.NewInstance.Filter.RefreshToken(userRefreshToken).Get.FirstOrDefault(); if (userLogin != null)/*&& user?.RefreshTokenEndDate > DateTime.Now*/ { TokenHandler tokenHandler = new TokenHandler(configuration); Token.Token token = tokenHandler.CreateAccessToken(userLogin); userLogin.RefreshToken = token.RefreshToken; userLogin.RefreshTokenEndDate = token.Expiration.AddMinutes(3); var updateRefresh = UserLoginRepo.NewInstance.Do.Update(userLogin); var claims = new List <Claim> { new Claim(ClaimTypes.Sid, userLogin.UserId.ToString()), new Claim(ClaimTypes.NameIdentifier, userLogin.RefreshToken), new Claim(ClaimTypes.Name, userLogin.Name + " " + userLogin.Surname), new Claim(ClaimTypes.Email, userLogin.Email), }; var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); var principal = new ClaimsPrincipal(identity); var props = new AuthenticationProperties(); HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, props); return(Json(new { result = true })); } return(Json(new { result = false })); }
public async Task <IActionResult> Login([FromBody] User user) { var userInSystemToVerifyAgainst = await _userService.GetByNameAsync(user.Name); var loginOk = _authenticationService.CheckUserLogin(userInSystemToVerifyAgainst, user.Password); if (!loginOk) { return(Unauthorized()); } var accessToken = _tokenHandler.CreateAccessToken(userInSystemToVerifyAgainst); return(Ok(accessToken)); }
public Token RefreshTokenLogin([FromBody] User refreshToken) { User user = _userRepo.FirstOrDefault(x => x.RefreshToken == refreshToken.RefreshToken); if (user != null && user?.RefreshTokenEndDate > DateTime.Now) { TokenHandler tokenHandler = new TokenHandler(_configuration); Token token = tokenHandler.CreateAccessToken(user); user.RefreshToken = token.RefreshToken; user.RefreshTokenEndDate = token.Expiration.AddMinutes(3); return(token); } return(null); }
public IActionResult RefreshTokenLogin([FromForm] string refreshToken) { var user = _userRepository.GetUserByRefreshToken(refreshToken); if (user != null && user?.DRefreshTokenEndDate > DateTime.Now) { TokenHandler tokenHandler = new TokenHandler(_configuration); var token = tokenHandler.CreateAccessToken(user); _userRepository.UpdateUserRefreshToken(user.IUserId, token.RefreshToken, DateTime.Now.AddDays(30)); return(Ok(token)); } throw new ApiException("Kullanıcı bulunamadı."); }
public async Task Login(string userName, string password) { User user = await _context.Users.FirstOrDefaultAsync(u => u.Username == userName && u.Password == password); Token token = null; if (user != null) { TokenHandler tokenHandler = new TokenHandler(_configuration); token = tokenHandler.CreateAccessToken(5); user.RefreshToken = token.RefreshToken; user.RefreshTokenEndDate = token.Expiration.AddMinutes(3); await _context.SaveChangesAsync(); } await Clients.Caller.Login(user != null?token : null); }
public async Task RefreshTokenLogin(string refreshToken) { User user = StaticDatas.Users.FirstOrDefault(x => x.RefreshToken == refreshToken); Token token = null; if (user != null && user?.RefreshTokenEndDate > DateTime.Now) { TokenHandler tokenHandler = new TokenHandler(_configuration); token = tokenHandler.CreateAccessToken(10); user.RefreshToken = token.RefreshToken; user.RefreshTokenEndDate = token.Expiration.AddMinutes(10); } await Clients.Caller.SendAsync("Login", user != null?token : null); }
public async Task <IActionResult> RefreshTokenLogin([FromForm] string refreshToken) { var user = _repoWrapper.User.FindByCondition(x => x.RefreshToken == refreshToken).FirstOrDefault(); if (user != null && user?.RefreshTokenEndDate > DateTime.Now) { TokenHandler tokenHandler = new TokenHandler(_configuration); Token token = tokenHandler.CreateAccessToken(user); user.RefreshToken = token.RefreshToken; user.RefreshTokenEndDate = token.Expiration.AddMinutes(3); await _repoWrapper.SaveAsync(); return(Ok(token)); } return(NotFound()); }
public IActionResult RefreshTokenLogin(string refreshToken) { User user = _northwindContext.Users.FirstOrDefault(x => x.RefreshToken == refreshToken); if (user != null && user.RefreshTokenEndDate > DateTime.UtcNow) { TokenHandler tokenHandler = new TokenHandler(_configuration); Token token = tokenHandler.CreateAccessToken(user); user.RefreshToken = token.RefreshToken; user.RefreshTokenEndDate = token.Expiration.AddSeconds(10); _northwindContext.SaveChanges(); return(Ok(token)); } return(new StatusCodeResult(401)); }
public async Task RefreshTokenLogin(string refreshToken) { User user = await _context.Users.FirstOrDefaultAsync(x => x.RefreshToken == refreshToken); Token token = null; if (user != null && user?.RefreshTokenEndDate > DateTime.Now) { TokenHandler tokenHandler = new TokenHandler(_configuration); token = tokenHandler.CreateAccessToken(1); user.RefreshToken = token.RefreshToken; user.RefreshTokenEndDate = token.Expiration.AddMinutes(1); await _context.SaveChangesAsync(); } await Clients.Caller.Login(user != null?token : null); }
public async Task Login(string userName, string password) { User user = StaticDatas.Users .FirstOrDefault(u => u.Username == userName && u.Password == password); Token token = null; if (user != null) { TokenHandler tokenHandler = new TokenHandler(_configuration); token = tokenHandler.CreateAccessToken(10); user.RefreshToken = token.RefreshToken; user.RefreshTokenEndDate = token.Expiration.AddMinutes(10); } await Clients.Caller.SendAsync("Login", user != null?token : null); }
public Token Login([FromBody] UserLogin userLogin) { User user = _userRepo.FirstOrDefault(x => x.Email == userLogin.Email && x.Password == userLogin.Password); if (user != null) { //Token üretiliyor. TokenHandler tokenHandler = new TokenHandler(_configuration); Token token = tokenHandler.CreateAccessToken(user); //Refresh token Users tablosuna işleniyor. user.RefreshToken = token.RefreshToken; user.RefreshTokenEndDate = token.Expiration.AddMinutes(3); return(token); } return(null); }
public async Task <TokenAuthentication.Models.Token> RefreshTokenLogin([FromForm] string refreshToken) { User user = await _context.Users.FirstOrDefaultAsync(x => x.RefreshToken == refreshToken); if (user != null && user?.RefreshTokenEndDate > DateTime.Now) { TokenHandler tokenHandler = new TokenHandler(_configuration); TokenAuthentication.Models.Token token = tokenHandler.CreateAccessToken(user); user.RefreshToken = token.RefreshToken; user.RefreshTokenEndDate = token.Expiration.AddMinutes(3); await _context.SaveChangesAsync(); return(token); } return(null); }
public IActionResult Login(UserLoginVM user) { User getUser = _context.Users.FirstOrDefault(d => d.Username == user.Username && d.Password == user.Password); if (getUser != null) { TokenHandler tokenHandler = new TokenHandler(_configuration); Token token = tokenHandler.CreateAccessToken(getUser); getUser.RefreshToken = token.RefreshToken; getUser.RefreshTokenEndDate = token.Expiration.AddSeconds(30); _context.SaveChanges(); return(Ok(token)); } return(Ok("Kullanıcı adı veya şifre yanlış!")); }
public async Task <TokenAuthentication.Models.Token> Login([FromForm] UserLogin userLogin) { User user = await _context.Users.FirstOrDefaultAsync(x => x.Email == userLogin.Email && x.Password == userLogin.Password); if (user != null) { //Token üretiliyor. TokenHandler tokenHandler = new TokenHandler(_configuration); TokenAuthentication.Models.Token token = tokenHandler.CreateAccessToken(user); //Refresh token Users tablosuna işleniyor. user.RefreshToken = token.RefreshToken; user.RefreshTokenEndDate = token.Expiration.AddMinutes(3); await _context.SaveChangesAsync(); return(token); } return(null); }
public async Task <Token> Authenticate([FromBody] AuthenticateRequest request) { User user = await _context.Users.FirstOrDefaultAsync(x => x.Username == request.Username && x.Password == request.Password); if (user == null) { return(null); } //Token üretiliyor. TokenHandler tokenHandler = new TokenHandler(_configuration); Token token = tokenHandler.CreateAccessToken(user); //Refresh token Users tablosuna işleniyor. user.RefreshToken = token.RefreshToken; user.RefreshTokenEndDate = token.Expiration.AddMinutes(3); await _context.SaveChangesAsync(); return(token); }
public ActionResult <DtoUser> Post(DtoUser paramUser) { var rm = new RedisCacheManager(); if (rm.Count() >= activeUserLimit) { return(Forbid()); } var user = _userContext.users.Where(u => u.username.Equals(paramUser.username) && u.password.Equals(paramUser.password)).FirstOrDefault(); if (user == null) { return(Forbid()); } var session = rm.Get(user.id.ToString()); if (!string.IsNullOrEmpty(session)) { return(Forbid()); } TokenHandler tokenHandler = new TokenHandler(); Token token = tokenHandler.CreateAccessToken(user.id); //Refresh token Users tablosuna işleniyor. user.refreshtoken = token.RefreshToken; user.refreshtokenexpirationdate = token.Expiration.AddMinutes(20); _userContext.SaveChanges(); //write to redis rm.Set(user.id.ToString(), token.AccessToken, 300); return(Ok(new DtoUser { authToken = token.AccessToken, name = user.name, surname = user.surname, refreshToken = token.RefreshToken })); }
public async Task <IActionResult> Login(object postData) { var loginData = JsonConvert.DeserializeObject <LoginData>(postData.ToString());//postData.ToObject<LoginData>(); var userData = _repoWrapper.User.FindByCondition(x => x.Email == loginData.Email && x.Password == loginData.Password).FirstOrDefault(); if (userData != null) { TokenHandler tokenHandler = new TokenHandler(_configuration); Token token = tokenHandler.CreateAccessToken(userData); //Refresh token Users tablosuna işleniyor. userData.AccesToken = token.AccessToken; userData.RefreshToken = token.RefreshToken; userData.RefreshTokenEndDate = token.Expiration.AddMinutes(3); await _repoWrapper.SaveAsync(); return(Ok(token)); } return(NotFound()); }
public IActionResult Login(UserCreateOrLoginVM model) { User user = _northwindContext.Users.FirstOrDefault(u => u.Username == model.Username && u.Password == model.Password); if (user != null) { TokenHandler tokenHandler = new TokenHandler(_configuration); Token token = tokenHandler.CreateAccessToken(user); user.RefreshToken = token.RefreshToken; user.RefreshTokenEndDate = token.Expiration.AddSeconds(30); _northwindContext.SaveChanges(); return(Ok(token)); } return(Ok(new { Message = "Username or Password wrong" })); }
public IActionResult Login([FromForm] LoginModel model) { if (_userRepository.CheckEmail(model.Username)) { throw new ApiException("Bu mail adresi ile tanımlı bir kullanıcı bulunmamaktadır."); } var user = _userRepository.Login(model.Username, model.Password); if (user == null) { throw new ApiException("Kullanıcı adı veya şifre yanlış."); } TokenHandler tokenHandler = new TokenHandler(_configuration); var token = tokenHandler.CreateAccessToken(user); _userRepository.UpdateUserRefreshToken(user.IUserId, token.RefreshToken, DateTime.Now.AddDays(30)); return(Ok(token)); }
public JsonResult UserLogin(string username, string password) { var userLogin = UserLoginRepo.NewInstance.Filter.UserLogin(username, password).Get.FirstOrDefault(); if (userLogin == null || !BC.Verify(password, userLogin.Password)) { return(Json(new { result = false })); } else { //Token üretiliyor. TokenHandler tokenHandler = new TokenHandler(configuration); Token.Token token = tokenHandler.CreateAccessToken(userLogin); //Refresh token Users tablosuna işleniyor. userLogin.RefreshToken = token.RefreshToken; userLogin.RefreshTokenEndDate = token.Expiration.AddMinutes(3); var updateRefresh = UserLoginRepo.NewInstance.Do.Update(userLogin); var claims = new List <Claim> { new Claim(ClaimTypes.Sid, userLogin.UserId.ToString()), new Claim(ClaimTypes.NameIdentifier, userLogin.RefreshToken), new Claim(ClaimTypes.Name, userLogin.Name + " " + userLogin.Surname), new Claim(ClaimTypes.Email, userLogin.Email) }; var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); var principal = new ClaimsPrincipal(identity); var props = new AuthenticationProperties(); HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, props); return(Json(new { result = true })); } }
public IActionResult Login(string userName, string password) { TokenHandler._configuration = _configuration; return(Ok(userName == "gncy" && password == "12345" ? TokenHandler.CreateAccessToken() : new UnauthorizedResult())); }