Implement Secure Refresh Token Rotation with Revocation Support
This commit is contained in:
committed by
Aditya Chandel
parent
277b82263d
commit
2407cf93fa
+38
-9
@@ -5,6 +5,8 @@ import com.adityachandel.booklore.exception.ApiError;
|
|||||||
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||||
import com.adityachandel.booklore.model.dto.request.UserLoginRequest;
|
import com.adityachandel.booklore.model.dto.request.UserLoginRequest;
|
||||||
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||||
|
import com.adityachandel.booklore.model.entity.RefreshTokenEntity;
|
||||||
|
import com.adityachandel.booklore.repository.RefreshTokenRepository;
|
||||||
import com.adityachandel.booklore.repository.UserRepository;
|
import com.adityachandel.booklore.repository.UserRepository;
|
||||||
import com.adityachandel.booklore.service.user.UserCreatorService;
|
import com.adityachandel.booklore.service.user.UserCreatorService;
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
@@ -14,6 +16,7 @@ import org.springframework.security.core.context.SecurityContextHolder;
|
|||||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.util.Date;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
|
|
||||||
@@ -23,6 +26,7 @@ public class AuthenticationService {
|
|||||||
|
|
||||||
private final AppProperties appProperties;
|
private final AppProperties appProperties;
|
||||||
private final UserRepository userRepository;
|
private final UserRepository userRepository;
|
||||||
|
private final RefreshTokenRepository refreshTokenRepository;
|
||||||
private final UserCreatorService userCreatorService;
|
private final UserCreatorService userCreatorService;
|
||||||
private final PasswordEncoder passwordEncoder;
|
private final PasswordEncoder passwordEncoder;
|
||||||
private final JwtUtils jwtUtils;
|
private final JwtUtils jwtUtils;
|
||||||
@@ -33,7 +37,8 @@ public class AuthenticationService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public ResponseEntity<Map<String, String>> loginUser(UserLoginRequest loginRequest) {
|
public ResponseEntity<Map<String, String>> loginUser(UserLoginRequest loginRequest) {
|
||||||
BookLoreUserEntity user = userRepository.findByUsername(loginRequest.getUsername()).orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(loginRequest.getUsername()));
|
BookLoreUserEntity user = userRepository.findByUsername(loginRequest.getUsername())
|
||||||
|
.orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(loginRequest.getUsername()));
|
||||||
|
|
||||||
if (!passwordEncoder.matches(loginRequest.getPassword(), user.getPasswordHash())) {
|
if (!passwordEncoder.matches(loginRequest.getPassword(), user.getPasswordHash())) {
|
||||||
throw ApiError.INVALID_CREDENTIALS.createException();
|
throw ApiError.INVALID_CREDENTIALS.createException();
|
||||||
@@ -63,24 +68,48 @@ public class AuthenticationService {
|
|||||||
String accessToken = jwtUtils.generateAccessToken(user);
|
String accessToken = jwtUtils.generateAccessToken(user);
|
||||||
String refreshToken = jwtUtils.generateRefreshToken(user);
|
String refreshToken = jwtUtils.generateRefreshToken(user);
|
||||||
|
|
||||||
|
RefreshTokenEntity refreshTokenEntity = RefreshTokenEntity.builder()
|
||||||
|
.user(user)
|
||||||
|
.token(refreshToken)
|
||||||
|
.expiryDate(new Date(System.currentTimeMillis() + jwtUtils.getRefreshTokenExpirationMs()))
|
||||||
|
.revoked(false)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
refreshTokenRepository.save(refreshTokenEntity);
|
||||||
|
|
||||||
return ResponseEntity.ok(Map.of(
|
return ResponseEntity.ok(Map.of(
|
||||||
"accessToken", accessToken,
|
"accessToken", accessToken,
|
||||||
"refreshToken", refreshToken,
|
"refreshToken", refreshTokenEntity.getToken(),
|
||||||
"isDefaultPassword", String.valueOf(user.isDefaultPassword())
|
"isDefaultPassword", String.valueOf(user.isDefaultPassword())
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
public ResponseEntity<Map<String, String>> refreshToken(String refreshToken) {
|
public ResponseEntity<Map<String, String>> refreshToken(String token) {
|
||||||
if (!jwtUtils.validateToken(refreshToken)) {
|
RefreshTokenEntity storedToken = refreshTokenRepository.findByToken(token).orElseThrow(() -> ApiError.INVALID_CREDENTIALS.createException("Refresh token not found"));
|
||||||
throw ApiError.INVALID_CREDENTIALS.createException();
|
|
||||||
|
if (storedToken.isRevoked() || storedToken.getExpiryDate().before(new Date()) || !jwtUtils.validateToken(token)) {
|
||||||
|
throw ApiError.INVALID_CREDENTIALS.createException("Invalid or expired refresh token");
|
||||||
}
|
}
|
||||||
|
|
||||||
String username = jwtUtils.extractUsername(refreshToken);
|
BookLoreUserEntity user = storedToken.getUser();
|
||||||
BookLoreUserEntity user = userRepository.findByUsername(username).orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(username));
|
|
||||||
|
storedToken.setRevoked(true);
|
||||||
|
storedToken.setRevocationDate(new Date());
|
||||||
|
refreshTokenRepository.save(storedToken);
|
||||||
|
|
||||||
String newAccessToken = jwtUtils.generateAccessToken(user);
|
|
||||||
String newRefreshToken = jwtUtils.generateRefreshToken(user);
|
String newRefreshToken = jwtUtils.generateRefreshToken(user);
|
||||||
|
RefreshTokenEntity newRefreshTokenEntity = RefreshTokenEntity.builder()
|
||||||
|
.user(user)
|
||||||
|
.token(newRefreshToken)
|
||||||
|
.expiryDate(new Date(System.currentTimeMillis() + jwtUtils.getRefreshTokenExpirationMs()))
|
||||||
|
.revoked(false)
|
||||||
|
.build();
|
||||||
|
|
||||||
return ResponseEntity.ok(Map.of("accessToken", newAccessToken, "refreshToken", newRefreshToken));
|
refreshTokenRepository.save(newRefreshTokenEntity);
|
||||||
|
|
||||||
|
return ResponseEntity.ok(Map.of(
|
||||||
|
"accessToken", jwtUtils.generateAccessToken(user),
|
||||||
|
"refreshToken", newRefreshToken
|
||||||
|
));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+13
-15
@@ -1,31 +1,33 @@
|
|||||||
package com.adityachandel.booklore.config.security;
|
package com.adityachandel.booklore.config.security;
|
||||||
|
|
||||||
import io.jsonwebtoken.*;
|
|
||||||
import io.jsonwebtoken.security.Keys;
|
|
||||||
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||||
import com.adityachandel.booklore.service.JwtSecretService;
|
import com.adityachandel.booklore.service.JwtSecretService;
|
||||||
|
import io.jsonwebtoken.Claims;
|
||||||
|
import io.jsonwebtoken.ExpiredJwtException;
|
||||||
|
import io.jsonwebtoken.JwtException;
|
||||||
|
import io.jsonwebtoken.Jwts;
|
||||||
|
import io.jsonwebtoken.security.Keys;
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
import javax.crypto.SecretKey;
|
import javax.crypto.SecretKey;
|
||||||
import java.util.Date;
|
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.Date;
|
||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@Service
|
@Service
|
||||||
@Component
|
@Component
|
||||||
|
@RequiredArgsConstructor
|
||||||
public class JwtUtils {
|
public class JwtUtils {
|
||||||
|
|
||||||
private final JwtSecretService jwtSecretService;
|
private final JwtSecretService jwtSecretService;
|
||||||
private final long accessTokenExpirationMs;
|
@Getter
|
||||||
private final long refreshTokenExpirationMs;
|
public final long accessTokenExpirationMs = 1000L * 60 * 60 * 10; // 10 hours
|
||||||
|
@Getter
|
||||||
public JwtUtils(JwtSecretService jwtSecretService) {
|
public final long refreshTokenExpirationMs = 1000L * 60 * 60 * 24 * 30; // 30 days
|
||||||
this.jwtSecretService = jwtSecretService;
|
|
||||||
this.accessTokenExpirationMs = 36000000; // 10 hours
|
|
||||||
this.refreshTokenExpirationMs = 604800000; // 7 days
|
|
||||||
}
|
|
||||||
|
|
||||||
private SecretKey getSigningKey() {
|
private SecretKey getSigningKey() {
|
||||||
String secretKey = jwtSecretService.getSecret();
|
String secretKey = jwtSecretService.getSecret();
|
||||||
@@ -83,8 +85,4 @@ public class JwtUtils {
|
|||||||
}
|
}
|
||||||
throw new IllegalArgumentException("Invalid userId claim type");
|
throw new IllegalArgumentException("Invalid userId claim type");
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean isTokenExpired(String token) {
|
|
||||||
return extractClaims(token).getExpiration().before(new Date());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
+36
@@ -0,0 +1,36 @@
|
|||||||
|
package com.adityachandel.booklore.model.entity;
|
||||||
|
|
||||||
|
import jakarta.persistence.*;
|
||||||
|
import lombok.*;
|
||||||
|
|
||||||
|
import java.util.Date;
|
||||||
|
|
||||||
|
@Entity
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
@Table(name = "refresh_token")
|
||||||
|
public class RefreshTokenEntity {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
@Column(nullable = false, unique = true, length = 512)
|
||||||
|
private String token;
|
||||||
|
|
||||||
|
@OneToOne
|
||||||
|
@JoinColumn(name = "user_id", referencedColumnName = "id")
|
||||||
|
private BookLoreUserEntity user;
|
||||||
|
|
||||||
|
@Column(name = "expiry_date", nullable = false)
|
||||||
|
private Date expiryDate;
|
||||||
|
|
||||||
|
@Column(nullable = false)
|
||||||
|
private boolean revoked = false;
|
||||||
|
|
||||||
|
@Column(name = "revocation_date")
|
||||||
|
private Date revocationDate;
|
||||||
|
}
|
||||||
+12
@@ -0,0 +1,12 @@
|
|||||||
|
package com.adityachandel.booklore.repository;
|
||||||
|
|
||||||
|
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||||
|
import com.adityachandel.booklore.model.entity.RefreshTokenEntity;
|
||||||
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
public interface RefreshTokenRepository extends JpaRepository<RefreshTokenEntity, Long> {
|
||||||
|
Optional<RefreshTokenEntity> findByToken(String token);
|
||||||
|
void deleteByUser(BookLoreUserEntity user);
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
CREATE TABLE refresh_token
|
||||||
|
(
|
||||||
|
id BIGINT PRIMARY KEY AUTO_INCREMENT,
|
||||||
|
user_id BIGINT NOT NULL,
|
||||||
|
token VARCHAR(512) NOT NULL,
|
||||||
|
expiry_date TIMESTAMP NOT NULL,
|
||||||
|
revoked BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
|
revocation_date TIMESTAMP NULL,
|
||||||
|
|
||||||
|
CONSTRAINT uq_refresh_token UNIQUE (token),
|
||||||
|
CONSTRAINT fk_refresh_token_user FOREIGN KEY (user_id)
|
||||||
|
REFERENCES users (id)
|
||||||
|
ON DELETE CASCADE
|
||||||
|
);
|
||||||
Reference in New Issue
Block a user