public bool ValidRefreshToken(String _token) { try { JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler(); JwtSecurityToken jwtToken = tokenHandler.ReadToken(_token) as JwtSecurityToken; UserRefreshToken token = new UserRefreshToken { RefreshToken = _token, Id = Convert.ToInt32(jwtToken.Claims.FirstOrDefault(claim => claim.Type == "email").Value), User = Convert.ToInt32(jwtToken.Claims.FirstOrDefault(claim => claim.Type == "unique_name").Value) }; var key = Encoding.ASCII.GetBytes(_secret2); tokenHandler.ValidateToken(token.RefreshToken, new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(key), ValidateIssuer = false, ValidateAudience = false, ValidateLifetime = true }, out SecurityToken validatedRefreshToken); var t = _context.GetById(token.Id); if (t == null || t.User != token.User || String.Compare(t.RefreshToken, _token) != 0) { throw new Exception("Token doesn't exist"); } return(true); }catch (SecurityTokenExpiredException e) { Console.WriteLine(e.Message); throw new Exception(e.Message); } }
public async Task Delete_ReturnsDeletedToken() { string usersJson = File.ReadAllText(TestConfiguration.MockDataFolderPath + @"Users.json"); var user = JsonConvert.DeserializeObject <List <User> >(usersJson).First(u => u.Id == TESTING_USER_ID); const int refreshTokenId = 2; const string token = "qqqqqqqqqqqqqqqqqqqqqqqwwwwwwwee"; DateTime expirationDate = DateTime.Now.AddMinutes(5); var newRefreshToken = new UserRefreshToken { Id = refreshTokenId, User = user, Token = token, ExpiredDate = expirationDate }; UserRefreshTokenRepository.Setup(r => r.GetByKey(newRefreshToken.Id)).Returns(newRefreshToken); UserRefreshTokenRepository.Setup(r => r.Delete(newRefreshToken.Id)).ReturnsAsync(newRefreshToken); var resultToken = await UserRefreshTokenService.Delete(newRefreshToken.Id); Assert.NotNull(resultToken); Assert.NotNull(resultToken.User); Assert.Equal(TESTING_USER_ID, resultToken.User.Id); Assert.Equal(token, resultToken.Token); Assert.Equal(expirationDate, resultToken.ExpiredDate); }
public async Task <UserRefreshToken> GetRefreshTokenByUserId(int userId) { UserRefreshToken userRefreshToken = new UserRefreshToken(); try { using (SqlConnection cn = new SqlConnection(this.ConnectionString)) using (SqlCommand cmd = new SqlCommand(RefreshTokenQueries.SelectRefreshTokenByUserId(), cn)) { cmd.Parameters.Add("@UserId", SqlDbType.Int).Value = userId; await cn.OpenAsync(); SqlDataReader reader = await cmd.ExecuteReaderAsync(); while (await reader.ReadAsync()) { userRefreshToken.Id = Convert.ToInt32(reader["Id"]); userRefreshToken.UserId = Convert.ToInt32(reader["UserId"]); userRefreshToken.RefreshToken = reader["RefreshToken"].ToString(); } } } catch (Exception ex) { this.logger.LogError(ex.Message); throw ex; } if (string.IsNullOrWhiteSpace(userRefreshToken.RefreshToken)) { return(null); } return(userRefreshToken); }
public async Task Should_add_and_get_token_per_device() { // given var now = DateTime.UtcNow; string email = "*****@*****.**"; string firstRefreshToken = "F5 F5"; string firstDeviceIpAddress = "8.8.8.8"; string secondRefreshToken = "F6 F6"; string secondDeviceIpAddress = "8.8.8.9"; UserRefreshTokenRepository repository = CreateRepository(); // when await repository.AddRefreshToken(email, firstRefreshToken, firstDeviceIpAddress); await repository.AddRefreshToken(email, secondRefreshToken, secondDeviceIpAddress); UserRefreshToken token = await repository.GetRefreshToken(email, firstDeviceIpAddress); // then token.ShouldNotBeNull(); token.Email.ShouldBe(email); token.RefreshToken.ShouldBe(firstRefreshToken); token.CreationDate.ShouldBeGreaterThanOrEqualTo(now); token.IpAddress.ShouldBe(firstDeviceIpAddress); }
public async Task Should_remove_token_per_device() { // given var now = DateTime.UtcNow; string email = "*****@*****.**"; string firstRefreshToken = "F5 F5"; string firstDeviceIpAddress = "8.8.8.8"; string secondRefreshToken = "F6 F6"; string secondDeviceIpAddress = "8.8.8.9"; UserRefreshTokenRepository repository = CreateRepository(); // when await repository.AddRefreshToken(email, firstRefreshToken, firstDeviceIpAddress); await repository.AddRefreshToken(email, secondRefreshToken, secondDeviceIpAddress); await repository.DeleteRefreshTokens(email, firstDeviceIpAddress); // then UserRefreshToken token1 = await repository.GetRefreshToken(email, firstDeviceIpAddress); UserRefreshToken token2 = await repository.GetRefreshToken(email, secondDeviceIpAddress); token1.ShouldBeNull(); token2.ShouldNotBeNull(); }
public async Task <ServiceResult> SignInWithForm([FromBody] UserLoginViewModel userLoginViewModel) { var serviceResult = await _userService.SignInWithFormAsync(userLoginViewModel); if (serviceResult.MessageType != Todo.Core.Enums.EMessageType.Success) { return(serviceResult); } var user = (User)serviceResult.Result; _userService.RemoveOldRefreshTokensAsync(user.Id); var newRefreshToken = new UserRefreshToken { UserId = user.Id, Token = Guid.NewGuid().ToString(), IssuedUtc = _jwtOptions.IssuedAt, ExpiresUtc = _jwtOptions.RefreshTokenExpiration }; await _userService.AddRefreshTokenAsync(newRefreshToken); var jwt = await _jwtFactory.GenerateEncodedToken(user, newRefreshToken); serviceResult = new ServiceResult { Result = jwt, MessageType = Todo.Core.Enums.EMessageType.Success }; return(serviceResult); }
public async Task <string> CreateRefreshToken(string email, string ipAddress) { string refreshToken = Guid.NewGuid().ToString("N"); UserRefreshToken userRefreshToken = await _refreshTokenRepository.AddRefreshToken(email, refreshToken, ipAddress); return(userRefreshToken.RefreshToken); }
public async Task <object> RefreshToken(string id, string RefreshToken, string refreshToken) { var user = await _userReporitory.GetRefreshToken(id); if (user is null || user.UserRefreshTokens?.Count() <= 0) { return(null); } if (!user.IsValidRefreshToken(RefreshToken)) { return(null); } UserRefreshToken refresh = user.UserRefreshTokens.Where(o => o.Token == RefreshToken).FirstOrDefault(); if (!_RefreshTokenRepository.Delete(refresh)) { return(null); } user.CreateRefreshToken(refreshToken, user.UserName); if (!await _userReporitory.Save(user)) { return(null); } IEnumerable <Claim> claims = new Claim[] { new Claim(JwtClaimTypes.Email, user.EMail), new Claim(JwtClaimTypes.Name, user.UserName), new Claim(JwtClaimTypes.Role, "admin"), }; return(claims); }
public async Task Should_remove_tokens_for_user_email() { // given string email1 = "*****@*****.**"; string tokenForUser1 = "token stuart 1"; string tokenForUser1_b = "token stuart 2"; string email2 = "*****@*****.**"; string tokenForUser2 = "token for bob"; UserRefreshTokenRepository repository = CreateRepository(); await repository.AddRefreshToken("jwt1", tokenForUser1, email1, "ip1"); await repository.AddRefreshToken("jwt2", tokenForUser1_b, email1, "ip2"); await repository.AddRefreshToken("jwt3", tokenForUser2, email2, "ip3"); // when await repository.DeleteRefreshTokens(email1); // then UserRefreshToken deletedToken1 = await repository.GetRefreshToken(tokenForUser1); UserRefreshToken deletedToken2 = await repository.GetRefreshToken(tokenForUser1_b); UserRefreshToken activeToken = await repository.GetRefreshToken(tokenForUser2); deletedToken1.ShouldBeNull(); deletedToken2.ShouldBeNull(); activeToken.ShouldNotBeNull(); }
public SignUpRespond signUp(SignUpRequest user) { User read = _userService.GetUserByEmail(user.Email); if (read != null) { throw new Exception("User has already exist"); } _userService.Insert(new User(user.Name, user.Email, BC.HashPassword(user.Password), user.Gender, user.ForgotPass, user.CityId, false)); read = _userService.GetUserByEmail(user.Email); string token = _jwtService.GenerateRefreshToken(read.Id); _tokenService.Insert(new UserRefreshToken { User = read.Id, RefreshToken = token, CreateAt = DateTime.Now, Device = user.Device }); UserRefreshToken refreshToken = _tokenService.GetTokenByToken(read.Id); return(new SignUpRespond(new ReadUserDto { Id = read.Id, Email = user.Email, IsActive = read.IsActive, Name = user.Name, IsAdmin = read.IsAdmin, Gender = user.Gender, CityId = user.CityId }, token)); }
/// <summary> /// RefreshToken revoke /// </summary> /// <param name="Request"></param> /// <returns></returns> public BaseResponse RevokeTokenRefresh(UpdateUserRefreshTokenRequest Request) { return(base.ExecuteWithExceptionHandledOperation(() => { BaseResponse response = new BaseResponse(); UserRefreshToken entity = _uof.UserRefreshTokenRepository.Find(x => x.Id == Request.Id && x.IsActive); if (entity == null) { response.IsSucceed = false; response.Message = "Güncellenecek refresh token bulunamadı."; response.ResultCode = (int)HttpStatusCode.NotFound; return response; } entity.IsActive = false; var resultUpdate = _uof.UserRefreshTokenRepository.Update(entity, Request.ClientUserId); if (resultUpdate == null) { response.IsSucceed = false; response.Message = "Refresh Token güncelleme işlemi başarısız."; response.ResultCode = (int)HttpStatusCode.NotFound; return response; } // Commit changes _uof.Commit(); return response; })); }
public async Task <UserRefreshToken> GetExistingRefreshToken(string existingRefreshToken) { if (string.IsNullOrEmpty(existingRefreshToken)) { return(null); } UserRefreshToken userRefreshToken = await _refreshTokenRepository.GetRefreshToken(existingRefreshToken); if (userRefreshToken != null) { var expireDate = userRefreshToken.CreationDate.AddDays(_jwtSettings.RefreshTokenExpiresDays); if (expireDate > DateTime.UtcNow) { try { ClaimsPrincipal principal = _tokenHandler.ValidateToken(userRefreshToken.JwtToken, _tokenValidationParameters, out SecurityToken securityToken); if (principal != null && securityToken != null) { return(userRefreshToken); } } catch (Exception e) { return(null); } } } return(null); }
public async Task <UserRefreshToken> Update(UserRefreshToken refreshToken) { ModelValidator.ValidateModelAttributes(refreshToken); Context.UserRefreshTokens.Update(refreshToken); await Context.SaveChangesAsync(); return(refreshToken); }
public async Task <ServiceResult> AddRefreshTokenAsync(UserRefreshToken userRefreshToken) { await _connectionFactory.GetConnection.InsertAsync <UserRefreshToken>(userRefreshToken); return(new ServiceResult { Result = userRefreshToken }); }
public bool CheckToken(string token, int id) { UserRefreshToken t = _tokenService.GetById(id); if (t != null && String.Compare(t.RefreshToken, token) == 0) { return(true); } return(false); }
public void SaveOrUpdateUserRefreshToken(UserRefreshToken userRefreshToken) { if (RefreshTokenStore.ContainsKey(userRefreshToken.Username)) { RefreshTokenStore[userRefreshToken.Username] = userRefreshToken.RefreshToken; } else { RefreshTokenStore.Add(userRefreshToken.Username, userRefreshToken.RefreshToken); } }
public void SaveRefreshToken(UserRefreshToken userRefreshToken) { if (RefreshTokenDict.ContainsKey(userRefreshToken.Email)) { RefreshTokenDict[userRefreshToken.Email] = userRefreshToken.RefreshToken; } else { RefreshTokenDict.Add(userRefreshToken.Email, userRefreshToken.RefreshToken); } }
public bool ActiveEmail(string token, int id) { if (CheckToken(token, id)) { UserRefreshToken t = _tokenService.GetById(id); User u = _userService.GetById(t.User); u.ConfirmedEmail = true; _userService.Update(u); return(true); } return(false); }
/// <summary> /// RefreshToken guncelle /// </summary> /// <param name="Request"></param> /// <returns></returns> public GetUserRefreshTokenResponse GetTokenRefresh(GetUserRefreshTokenRequest Request) { return(base.ExecuteWithExceptionHandledOperation(() => { GetUserRefreshTokenResponse response = new GetUserRefreshTokenResponse(); UserRefreshToken token = _uof.UserRefreshTokenRepository.GetRefreshTokenByToken(Request.RefreshToken); response.UserRefreshToken = _mapper.Map <UserRefreshTokenViewModel>(token); return response; })); }
public async Task <bool> IsRefreshTokenValidAsync(string userUUID, string refreshToken, CancellationToken ct = default) { UserRefreshToken token = await _context.UserRefreshTokens .AsNoTracking() .FirstOrDefaultAsync(t => t.UserUUID == userUUID && t.RefreshToken == refreshToken && t.TokenIsEnabled, ct); if (token != null) { return(token.TokenExpiryDate > DateTime.UtcNow && !await _userService.IsUserBannedAsync(userUUID)); } return(false); }
public async Task InvalidateRefreshTokenDoesNotBelongToUser() { var tokenValue = new byte[] { 0x01, 0x02, 0x03, 0x04 }; var tokenValueStr = Convert.ToBase64String(tokenValue); var momentMock = MomentTestHelper.CreateMomentMock(); using var testDb = new TestDatabase(this.outputHelper); using var identityInstance = IdentityTestHelper.CreateInstance(testDb, this.outputHelper); using var testDbContext = await testDb.CreateContextAsync().ConfigureAwait(true); var manager = new AuthManager( identityInstance.UserManager, testDbContext, momentMock.Object); var user = await identityInstance.CreateUserAsync("someone").ConfigureAwait(true); var user2 = await identityInstance.CreateUserAsync("someone1").ConfigureAwait(true); var claimsPrincipal = IdentityTestHelper.CreateClaimsPrincipalForUserId(user.Id); var tokenEntity = new UserRefreshToken { TokenValue = tokenValue, IpAddress = "1.2.3", UserAgent = "chrome", IsInvalidated = false, SubjectUserId = user2.Id, GeneratedAtUtc = momentMock.Object.UtcNow, ExpiresAtUtc = momentMock.Object.UtcNow.AddDays(1), ClientApplicationId = identityInstance.ClientId, }; testDbContext.UserRefreshTokens.Add(tokenEntity); await testDbContext.SaveChangesAsync().ConfigureAwait(true); var result = await manager.InvalidateRefreshTokenAsync( claimsPrincipal, tokenValueStr).ConfigureAwait(true); result.Should().BeFalse(because: "the token should not have been found and invalidated"); tokenEntity = await testDbContext.UserRefreshTokens .FindAsync(tokenValue) .ConfigureAwait(true); tokenEntity.IsInvalidated.Should().BeFalse( because: "the token was not invalidated"); }
private async Task <User> RefreshTokens(User user) { List <int> expiredTokensCheck = await CheckForExpired(user); //om tokens saknas eller refreshtoken är expired logga in på nytt if (user.JwtToken != null && user.RefreshToken != null && expiredTokensCheck[1] > 0) { UserRefreshToken refToken = new UserRefreshToken(); refToken.RefreshToken = user.RefreshToken; var jsonUser = new StringContent(JsonConvert.SerializeObject(refToken), Encoding.UTF8, "application/json"); var response = await client.PostAsync("https://localhost:5001/api/employees/refresh-token", jsonUser); string resultContent = response.Content.ReadAsStringAsync().Result; Console.WriteLine("Refreshing " + response.ReasonPhrase); var loginResponse = JsonConvert.DeserializeObject <LoginResponse>(resultContent); if (response.IsSuccessStatusCode) { using (var context = new AppDBContext()) { User saveToDb = context.Users.FirstOrDefault(u => u.UserName == loginResponse.UserName); saveToDb.UserName = loginResponse.UserName; saveToDb.JwtToken = loginResponse.JwtToken; saveToDb.JwtExpiresAt = loginResponse.JwtExpiresAt; saveToDb.RefreshToken = loginResponse.RefreshToken; saveToDb.RefExpiresAt = loginResponse.RefExpiresAt; context.SaveChanges(); } Console.WriteLine("Updating tokens for " + loginResponse.UserName); Console.WriteLine("Previous refresh token: "); Console.WriteLine(user.RefreshToken); Console.WriteLine("Current refresh token: "); Console.WriteLine(loginResponse.RefreshToken); } else { Console.WriteLine(resultContent); } User savedUser = await GetUserByName(user.UserName); return(savedUser); } Console.WriteLine("Token value is null or refToken is expired"); LoginUser loginUser = new LoginUser(); loginUser.UserName = user.UserName; loginUser.Password = "******"; User updatedUser = await Login(loginUser); return(updatedUser); }
public Task <UserRefreshToken> Update(UserRefreshToken refreshToken) { var token = RefreshTokenRepository.GetByKey(refreshToken.Id); if (token == null) { throw new CashSchedulerException("There is no such refresh token"); } token.Token = refreshToken.Token; token.ExpiredDate = refreshToken.ExpiredDate; return(RefreshTokenRepository.Update(token)); }
public async Task <BaseModel <UserModel> > Login(string email, string password) { BaseModel <UserModel> result = new BaseModel <UserModel>(); try { User user = await _users.Find(u => u.Email == email).FirstOrDefaultAsync(); if (user != null) { bool isVerified = VerifyPasswordHash(password, user.PasswordHash, user.PasswordSalt); if (isVerified) { string refreshToken = _passwordHasher.HashPassword(user, Guid.NewGuid().ToString()) .Replace("+", string.Empty) .Replace("=", string.Empty) .Replace("/", string.Empty); UserRefreshToken userRefreshToken = new UserRefreshToken() { UserId = user.Id, RefreshToken = refreshToken }; await _userRefreshTokens.InsertOneAsync(userRefreshToken); result.Data = new UserModel { Id = user.Id, Email = user.Email, CreatedAt = user.CreatedAt, Type = user.Type, RefreshToken = refreshToken }; string token = _jwtProvider.GenerateToken(result.Data); result.Data.Token = token; } } } catch { throw new SystemException("Something went wrong while verifiying user."); } return(result); }
public static UserRefreshToken GenerateRefreshToken() { UserRefreshToken refreshToken = new UserRefreshToken(); var randomNumber = new byte[32]; using (var rng = RandomNumberGenerator.Create()) { rng.GetBytes(randomNumber); refreshToken.Token = Convert.ToBase64String(randomNumber); } refreshToken.ExpiryDate = DateTime.UtcNow.AddMonths(6); return(refreshToken); }
public async void UpdateRefreshTokenMustUpdateRefreshTokenAndReturnNewRefreshTokenAsync() { var userRefreshToken = new UserRefreshToken { RefreshToken = "token" }; var mockClaim = new Mock <Claim>("uid", "id"); mockClaimsPrincipal.Setup(claimsPrincipal => claimsPrincipal.HasClaim(It.IsAny <Predicate <Claim> >())).Returns(true); mockClaimsPrincipal.Setup(claimsPrincipal => claimsPrincipal.FindFirst(It.IsAny <Predicate <Claim> >())).Returns(mockClaim.Object); mockRefreshRepository.Setup(refreshRepository => refreshRepository.GetByUserIdAsync(It.IsAny <string>())).ReturnsAsync(userRefreshToken); JwtService jwtService = new JwtService(mockRefreshRepository.Object, mockUserService.Object, mockConfiguration.Object); var actualRefreshToken = await jwtService.UpdateRefreshTokenAsync("token", mockClaimsPrincipal.Object); mockRefreshRepository.Verify(refreshRepository => refreshRepository.UpdateAsync(userRefreshToken), Times.Once); }
public async Task Should_remove_token() { // given string email1 = "*****@*****.**"; string refreshToken = "token stuart 1"; UserRefreshTokenRepository repository = CreateRepository(); await repository.AddRefreshToken("jwt1", refreshToken, email1, "ip1"); // when await repository.DeleteRefreshToken(refreshToken); // then UserRefreshToken deletedToken = await repository.GetRefreshToken(refreshToken); deletedToken.ShouldBeNull(); }
public async Task <BaseModel <UserModel> > RefreshAccessToken(string refreshToken) { BaseModel <UserModel> result = new BaseModel <UserModel>(); try { UserRefreshToken userRefreshToken = await _userRefreshTokens.Find(t => t.RefreshToken == refreshToken).FirstOrDefaultAsync(); if (userRefreshToken == null || userRefreshToken.IsRevoked) { result.HasError = true; result.ErrorMessage = "Refresh token not found or revoked."; return(result); } User user = await _users.Find(u => u.Id == userRefreshToken.UserId).FirstOrDefaultAsync(); if (user == null) { result.HasError = true; result.ErrorMessage = "User not found."; return(result); } result.Data = new UserModel { Id = user.Id, Email = user.Email, CreatedAt = user.CreatedAt, Type = user.Type, RefreshToken = refreshToken }; string token = _jwtProvider.GenerateToken(result.Data); result.Data.Token = token; } catch { throw new SystemException("Something went wrong while refreshing access token."); } return(result); }
public async Task <UserRefreshToken> AddRefreshToken(string jwtId, string refreshToken, string email, string ipAddress) { using (var session = _store.LightweightSession()) { var token = new UserRefreshToken() { JwtToken = jwtId, RefreshToken = refreshToken, CreationDate = DateTime.UtcNow, IpAddress = ipAddress, Email = email }; session.Store(token); await session.SaveChangesAsync(); return(token); } }
public void InitUser() { if (IsLoggedin()) { UserSaveLoad userSL = new UserSaveLoad(); userSL.LoadData(); HTTPRequest request = new HTTPRequest(new Uri(GlobalConst.UserLoginPath), OnRefreshRequestFinished); request.MethodType = BestHTTP.HTTPMethods.Post; request.AddHeader("Content-Type", "application/json;charset=utf-8"); UserRefreshToken urt = new UserRefreshToken(); urt.accessToken = userSL.myData._iUser.accessToken; urt.refreshToken = userSL.myData._iUser.refreshToken; urt.client = GlobalConst.ClientFlag + "-" + deviceFlag; string parm = JsonConvert.SerializeObject(urt); byte[] data = System.Text.UTF8Encoding.UTF8.GetBytes(parm); request.RawData = data; } }