public IActionResult RefreshToken([FromBody] RefreshTokenDTO refreshToken) { var user = _userProvider.GetAuthorizedUser(); if (user == null) { return(Unauthorized()); } var tokens = _authorizationService.RefreshToken(user, refreshToken.RefreshToken); return(Ok(tokens)); }
public async Task <IActionResult> Refresh([FromBody] RefreshTokenDTO tokenDto) { if (refreshTokenRepository.IsRefreshTokenActive(tokenDto.RefreshToken)) { var user = await userManager.FindByNameAsync(tokenDto.User.Username); var jwt = await GenerateJwt(user); return(Ok(new { jwt, tokenDto.RefreshToken })); } return(BadRequest("Invalid refresh token")); }
public async Task <IActionResult> RevokeRefreshToken(RefreshTokenDTO refreshTokenDTO) { IDataResult <AccessToken> result = await _iAuthenticationService.RevokeRefreshToken(refreshTokenDTO.RefreshToken); if (result.Success) { return(Ok(result.Data)); } else { return(BadRequest(result.Message)); } }
public void UpdateRefreshToken(RefreshTokenDTO refreshToken) { var _refreshToken = Database.RefreshTokens.GetById(refreshToken.Id); if (_refreshToken != null) { _refreshToken.Token = Guid.NewGuid().ToString(); Database.RefreshTokens.Update(_refreshToken.Id, _refreshToken); Database.Save(); } else { throw new RefreshTokenNotFoundException($"Refresh token \"{refreshToken}\" has not found"); } }
private static SqlCommand SQL_SAVE_REFRESHTOKEN(RefreshTokenDTO token) { string query = "INSERT INTO refresh_token ([token],[expires]" + ",[created_at],[created_by_ip],[user_id]) " + "VALUES(@token,@expires,@created_at,@created_by_ip,@user_id)"; var command = new SqlCommand(query); command.Parameters.AddWithValue("@token", token.Token); command.Parameters.AddWithValue("@expires", token.Expires); command.Parameters.AddWithValue("@created_at", token.CreatedAt); command.Parameters.AddWithValue("@created_by_ip", token.CreatedByIp); command.Parameters.AddWithValue("@user_id", token.UserId); return(command); }
public async Task <AuthResult> RefreshToken(RefreshTokenDTO model) { var principal = await GetCalimpPrincipalFromExpiredToken(model.Token); if (principal == null) { return(new AuthResult() { Message = ErrorMessage.TokenValidationFailed.GetDescription(), MessageType = nameof(ErrorMessage.EmailNotValid) }); } var expieryUnixDate = long.Parse(principal.Claims.SingleOrDefault(x => x.Type == JwtRegisteredClaimNames.Exp).Value); var expieryDateInUtc = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc) .AddSeconds(expieryUnixDate); //TODO this if (expieryDateInUtc > DateTime.UtcNow) { return(new AuthResult() { Message = ErrorMessage.TokenNotExpired.GetDescription(), MessageType = nameof(ErrorMessage.TokenNotExpired) }); } else { var tokenIdentifier = principal.Claims.Single(x => x.Type == JwtRegisteredClaimNames.Jti).Value; var refreshToken = await unitOfWork.TokenRepository.GetRefreshTokenForCurrentToken(model.RefreshToken); var rezult = ValidateToken(refreshToken, tokenIdentifier); if (rezult == null) { refreshToken.IsUsed = true; unitOfWork.TokenRepository.Update(refreshToken); await unitOfWork.Save(); var user = await unitOfWork.UserManager .FindByIdAsync(principal.Claims .Single(x => x.Type == ClaimTypes.NameIdentifier).Value); return(await GenerateJWTToken(user.Email)); } return(rezult); } }
public async Task <IActionResult> Refresh([FromBody] RefreshTokenDTO token) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var principal = GetPrincipalFromExpiredToken(token.Token); string name = null; name = principal.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier)?.Value; var identity = await GetClaimsIdentity(name, null, true); var jwt = await Tokens.GenerateJwt(identity, _jwtFactory, name, _jwtOptions, new JsonSerializerSettings { Formatting = Formatting.Indented }); return(new OkObjectResult(jwt)); }
private static SqlCommand SQL_UPDATE_REFRESHTOKEN(RefreshTokenDTO token) { string query = "UPDATE refresh_token SET revoked=@revoked, " + "revoked_by_ip=@revoked_by_ip, replaced_by_token=@replaced_by_token " + "WHERE token = @token"; var command = new SqlCommand(query); command.Parameters.AddWithValue("@token", token.Token); command.Parameters.AddWithValue("@revoked", token.Revoked); command.Parameters.AddWithValue("@revoked_by_ip", token.RevokedByIp); command.Parameters.AddWithValue("@replaced_by_token", Common.DbNullIfNull(token.ReplacedByToken)); return(command); }
public static RefreshToken FromRefreshTokenDTOToRefreshToken(RefreshTokenDTO token) { if (token == null) { return(null); } return(new RefreshToken { Id = token.Id, ClientId = token.ClientId, ExpiresUtc = token.ExpiresUtc, IssuedUtc = token.IssuedUtc, ProtectedTicket = token.ProtectedTicket, Subject = token.Subject }); }
public void SetUp() { RefreshToken = "4wjRDjmSi9YfgFYAVM2QWjJxY8w1Ao6U7S6ZWX9VDCQ="; DaysToExpire = 3; AccessToken = "4wjRDjmSi9YfgFYAVM2QWjJxY8w1Ao6U7S6ZWX9VDCQ"; Size = 32; UserId = 91; _userService = new Mock <IUserService>(); _tokenService = new Mock <ITokenService>(); theaterScheduleUnitOfWorkMock = new Mock <ITheaterScheduleUnitOfWork>(); _refreshTokenRepositoryMock = new Mock <IRefreshTokenRepository>(); _refreshTokenService = new RefreshTokenService(_refreshTokenRepositoryMock.Object, _tokenService.Object, _userService.Object, theaterScheduleUnitOfWorkMock.Object); _applicationUserDTO = new ApplicationUserDTO() { Id = 91, FirstName = "Volodya", LastName = "Khydzik", City = "Lviv", Country = "Lviv", Email = "*****@*****.**", PhoneNumber = "0672530997", DateOfBirth = "20.07.2000" }; _refreshTokenDTO = new RefreshTokenDTO() { Id = 1, IsActive = true, UserId = 91, RefreshToken = "4wjRDjmSi9YfgFYAVM2QWjJxY8w1Ao6U7S6ZWX9VDCQ =", DaysToExpire = DateTime.Now.AddDays(3) }; _refreshTokenModel = new RefreshTokenModel() { RefreshToken = "4wjRDjmSi9YfgFYAVM2QWjJxY8w1Ao6U7S6ZWX9VDCQ=" }; _tokenService.Setup(service => service.GenerateAccessToken(_applicationUserDTO, RefreshToken)).Returns(() => { return(AccessToken); }); }
public async Task <AccessTokenDTO> RefreshToken(RefreshTokenDTO dto) { var userId = _jwtFactory.GetUserIdFromToken(dto.AccessToken, dto.Key); //get userId from our access token var userEntity = _context.Users .Include(u => u.Avatar) .FirstOrDefault(x => x.Id == userId); //find user with such id if (userEntity == null) { _logger.LogWarning(LoggingEvents.HaveException, $"Not found user"); throw new NotFoundException(nameof(userEntity)); } var rToken = await _context.RefreshTokens.FirstOrDefaultAsync(t => t.Token == dto.RefreshToken && t.UserId == userId); // find such token for user if (rToken == null) { _logger.LogWarning(LoggingEvents.HaveException, $"invalid token"); throw new InvalidTokenException("refresh"); } if (!rToken.IsActive) { _logger.LogWarning(LoggingEvents.HaveException, $"expired refresh token"); throw new ExpiredRefreshTokenException(); } var jwtToken = await _jwtFactory.GenerateAccessToken(userEntity); //generate access token var refreshToken = JWTFactory.GenerateRefreshToken(); //generate random token _context.RefreshTokens.Remove(rToken); // remove previous one _context.RefreshTokens.Add(new RefreshToken //create new token { Token = refreshToken, UserId = userEntity.Id }); await _context.SaveChangesAsync(); return(new AccessTokenDTO(jwtToken, refreshToken)); //send to front generated tokens }
public async Task CreateAsync(AuthenticationTokenCreateContext context) { using (var requestScope = _ioc.BeginLifetimeScope("AutofacWebRequest")) { var tokenService = requestScope.Resolve(typeof(IRefreshTokenService)) as IRefreshTokenService; var clientId = context.Ticket.Properties.Dictionary["client_id"]; if (string.IsNullOrEmpty(clientId)) { await Task.CompletedTask; } var refreshTokenId = Guid.NewGuid().ToString("n"); var refreshTokenLifeTimeInDays = Convert.ToInt16(ConfigurationManager.AppSettings["RefreshTokenLifeTimeInDays"]); var token = new RefreshTokenDTO { Id = CryptoHelper.GetHash(refreshTokenId), Subject = context.Ticket.Identity.GetUserId(), IssuedUtc = DateTime.UtcNow, ExpiresUtc = DateTime.UtcNow.AddDays(refreshTokenLifeTimeInDays), OrganizationId = context.Ticket.Identity.GetOrganizationId() }; context.Ticket.Properties.IssuedUtc = token.IssuedUtc; context.Ticket.Properties.ExpiresUtc = token.ExpiresUtc; token.ProtectedTicket = context.SerializeTicket(); var userOrg = new UserAndOrganizationDTO { OrganizationId = context.Ticket.Identity.GetOrganizationId(), UserId = context.Ticket.Identity.GetUserId() }; tokenService?.RemoveTokenBySubject(userOrg); tokenService?.AddNewToken(token); context.SetToken(refreshTokenId); } await Task.CompletedTask; }
public async Task CreateRefreshToken(RefreshTokenDTO dto) { try { var existingToken = await _context.RefreshTokens.SingleOrDefaultAsync(x => x.Subject == dto.Subject && x.ClientId == dto.ClientType); if (existingToken != null) { _context.RefreshTokens.Remove(existingToken); await _context.SaveChangesAsync(); } await _context.RefreshTokens.AddAsync(_mapper.Map <RefreshToken>(dto)); await _context.SaveChangesAsync(); } catch (Exception) { // ignored } }
public async Task <IActionResult> refresh(RefreshTokenDTO refreshtoken) { try { var token = await _userservice.Refresh(refreshtoken); return(Ok(token)); } catch (Exception e) { if (e.Message.Length > 0) { return(BadRequest(e.Message)); } else { throw; } } }
public RefreshTokenDTO GetRefreshToken(string token) { RefreshTokenDTO refreshToken = null; using var connection = Common.GetConnection(); using var command = SQL_GET_REFRESHTOKEN(token); command.Connection = connection; connection.Open(); using var reader = command.ExecuteReader(); while (reader.Read()) { refreshToken = _refreshTokenMapper.Map(reader); } connection.Close(); return(refreshToken); }
public async Task <AuthResult> RevokeRefreshToken(RefreshTokenDTO model) { var refreshToken = await GetRefreshToken(model.Token); var rezult = ValidateToken(refreshToken, refreshToken.JwtId);//smth here if (rezult == null) { refreshToken.IsInvalidated = true; unitOfWork.TokenRepository.Update(refreshToken); await unitOfWork.Save(); //return new AuthResult() //{ // Message = ErrorMessage.TokenIsInvalidated.GetDescription(), // MessageType = nameof(ErrorMessage.TokenIsInvalidated) //}; } return(rezult); }
public void AddNewToken(RefreshTokenDTO tokenDto) { var timestamp = DateTime.UtcNow; var newToken = new RefreshToken { Id = tokenDto.Id, ExpiresUtc = tokenDto.ExpiresUtc, IssuedUtc = tokenDto.IssuedUtc, Subject = tokenDto.Subject, ProtectedTicket = tokenDto.ProtectedTicket, Created = timestamp, Modified = timestamp, OrganizationId = tokenDto.OrganizationId, CreatedBy = tokenDto.Subject, ModifiedBy = tokenDto.Subject }; _refreshTokensDbSet.Add(newToken); _uow.SaveChanges(false); }
public void SetUp() { DaysToExpire = 3; AccessToken = "4wjRDjmSi9YfgFYAVM2QWjJxY8w1Ao6U7S6ZWX9VDCQ"; Size = 32; UserId = 91; _userService = new Mock <IUserService>(); _refreshTokenService = new Mock <IRefreshTokenService>(); _tokenService = new Mock <ITokenService>(); _refreshTokenController = new RefreshTokenController(_tokenService.Object, _refreshTokenService.Object, _userService.Object); _applicationUserDTO = new ApplicationUserDTO() { Id = 91, FirstName = "Volodya", LastName = "Khydzik", City = "Lviv", Country = "Lviv", Email = "*****@*****.**", PhoneNumber = "0672530997", DateOfBirth = "20.07.2000" }; _refreshTokenDTO = new RefreshTokenDTO() { Id = 1, IsActive = true, UserId = 91, RefreshToken = "4wjRDjmSi9YfgFYAVM2QWjJxY8w1Ao6U7S6ZWX9VDCQ =", DaysToExpire = DateTime.Now.AddDays(3) }; _refreshTokenModel = new RefreshTokenModel() { RefreshToken = "4wjRDjmSi9YfgFYAVM2QWjJxY8w1Ao6U7S6ZWX9VDCQ=" }; _refreshTokenService.Setup(service => service.UpdateRefreshTokenAsync(_refreshTokenDTO.Id, _refreshTokenDTO.RefreshToken, _refreshTokenDTO.UserId, DaysToExpire, true)).Returns(Task.CompletedTask); _tokenService.Setup(service => service.GenerateAccessToken(_applicationUserDTO, _refreshTokenModel.RefreshToken)).Returns(() => { return(AccessToken); }); _refreshTokenService.Setup(service => service.GenerateRefreshToken(Size)).Returns(() => { return(_refreshTokenModel.RefreshToken); }); }
public async Task <IActionResult> RefreshToken(RefreshTokenDTO model) { try { var result = await _userService.RefreshToken(model); if (result == null) { return(BadRequest()); } return(Ok(result)); } catch (SecurityTokenException) { return(BadRequest()); } catch (ArgumentException) { return(BadRequest()); } }
public bool RevokeToken(string token, string ipAddress) { RefreshTokenDTO refreshToken = _refreshTokenRepository.GetRefreshToken(token); if (refreshToken == null) { return(false); } if (!refreshToken.IsActive) { return(false); } refreshToken.Revoked = DateTime.UtcNow; refreshToken.RevokedByIp = ipAddress; _refreshTokenRepository.UpdateRefreshToken(refreshToken); return(true); }
public async Task <IActionResult> Refresh( [FromBody] RefreshTokenDTO tokenDTO) { if (tokenDTO == null) { return(BadRequest(new AuthResponseDTO { IsAuthSuccessful = false, ErrorMessage = "Invalid client request" })); } var principal = _authenticationService.GetPrincipalFromExpiredToken(tokenDTO.Token); var username = principal.Identity.Name; var user = await _usermanager.FindByNameAsync(username); if (user == null || user.RefreshToken != tokenDTO.RefreshToken || user.RefreshTokenExpiryTime <= DateTime.Now) { return(BadRequest(new AuthResponseDTO { IsAuthSuccessful = false, ErrorMessage = "Invalid client request" })); } var token = await _authenticationService.GetToken(user); user.RefreshToken = _authenticationService.GenerateRefreshToken(); await _usermanager.UpdateAsync(user); return(Ok(new AuthResponseDTO { Token = token, RefreshToken = user.RefreshToken, IsAuthSuccessful = true })); }
private async Task <string> CreateRefreshToken(string clientType, string identityName) { var clientRefreshTokenLifeTime = await _accountService.GetClientRefreshTokenLifeTime(clientType); if (clientRefreshTokenLifeTime != null) { var refreshTokenId = GetHash(GenerateRandomCryptographicKey(_authOptions.Value.KeyLength)); var now = DateTime.UtcNow; var token = new RefreshTokenDTO { Id = GetHash(refreshTokenId), ClientType = clientType, Subject = identityName, IssuedUtc = now, ExpiresUtc = now.Add(TimeSpan.FromMinutes(clientRefreshTokenLifeTime.Value)) }; await _accountService.CreateRefreshToken(token); return(refreshTokenId); } return(null); }
public async Task CreateAsync(AuthenticationTokenCreateContext context) { _iAuthorizationBus = (IAuthorizationBus)GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(IAuthorizationBus)); var clientId = context.Ticket.Properties.Dictionary["as:client_id"]; if (string.IsNullOrEmpty(clientId)) { return; } var refreshTokenId = Guid.NewGuid().ToString("n"); var refreshTokenLifeTime = context.OwinContext.Get <string>("as:clientRefreshTokenLifeTime"); var token = new RefreshTokenDTO() { Id = Helper.GetHash(refreshTokenId), ClientId = clientId, Subject = context.Ticket.Identity.Name, IssuedUtc = DateTime.UtcNow, ExpiresUtc = DateTime.UtcNow.AddMinutes(Convert.ToDouble(refreshTokenLifeTime)) }; context.Ticket.Properties.IssuedUtc = token.IssuedUtc; context.Ticket.Properties.ExpiresUtc = token.ExpiresUtc; //TicketSerializer serializer = new TicketSerializer(); //token.ProtectedTicket = System.Text.Encoding.Default.GetString(serializer.Serialize(context.Ticket)); token.ProtectedTicket = context.SerializeTicket(); var result = await _iAuthorizationBus.AddRefreshToken(token); if (result) { context.SetToken(refreshTokenId); } }
public async Task <IActionResult> Refresh([FromBody] RefreshTokenDTO tokenDto) { if (tokenDto is null) { return(Unauthorized(new LoginResult { IsSuccessful = false, ErrorMessage = "Token is null" })); } var principal = _tokenService.GetPrincipalFromExpiredToken(tokenDto.AccessToken); var username = principal.Identity.Name; var user = _userManager.Users.SingleOrDefault(u => u.UserName == username); if (user == null || user.RefreshToken != tokenDto.RefreshToken || user.RefreshTokenExpiryTime <= DateTime.Now) { return(Unauthorized(new LoginResult { IsSuccessful = false, ErrorMessage = "Invalid client request" })); } var claims = await _tokenService.GetClaims(user); var newAccessToken = _tokenService.GenerateAccessToken(claims); var newRefreshToken = _tokenService.GenerateRefreshToken(); user.RefreshToken = newRefreshToken; user.RefreshTokenExpiryTime = DateTime.Now.AddDays(5); await _userManager.UpdateAsync(user); var response = new LoginResult { IsSuccessful = true, AccessToken = newAccessToken, RefreshToken = newRefreshToken }; return(Ok(response)); }
public async Task <AccessTokenDTO> RefreshToken(RefreshTokenDTO dto) { var userId = _jwtFactory.GetUserIdFromToken(dto.AccessToken, dto.SigningKey); var userEntity = await _context.Users.FindAsync(userId); if (userEntity == null) { throw new NotFoundException(nameof(User), userId); } var rToken = await _context.RefreshTokens.FirstOrDefaultAsync(t => t.Token == dto.RefreshToken && t.UserId == userId); if (rToken == null) { throw new InvalidTokenException("refresh"); } if (!rToken.IsActive) { throw new ExpiredRefreshTokenException(); } var jwtToken = await _jwtFactory.GenerateAccessToken(userEntity.Id, userEntity.UserName, userEntity.Email); var refreshToken = _jwtFactory.GenerateRefreshToken(); _context.RefreshTokens.Remove(rToken); // delete the token we've exchanged _context.RefreshTokens.Add(new RefreshToken // add the new one { Token = refreshToken, UserId = userEntity.Id }); await _context.SaveChangesAsync(); return(new AccessTokenDTO(jwtToken, refreshToken)); }
public async Task <ActionResult <AccessTokenDTO> > Refresh([FromBody] RefreshTokenDTO dto) { return(Ok(await _authService.RefreshToken(dto))); }
public async Task <Response> SignIn([FromBody] RefreshTokenDTO dto) { return(await _handler.RefreshToken(dto.RefreshToken)); }
public async Task <ActionResult <Response <TokenDTO> > > RefreshToken([Required] RefreshTokenDTO request) { return(await _handler.RefreshToken(request.RefreshToken)); }
public Task <TokensViewModel> RenewToken([FromBody] RefreshTokenDTO tokenDTO) { return(authService.RenewToken(tokenDTO)); }
public IActionResult RefreshToken([FromBody] RefreshTokenDTO refreshtoken) { return(Ok(_jwt.RefreshToken(refreshtoken))); }