WIP: Refresh token implemented in BE, yet to be implemented in FE

This commit is contained in:
aditya.chandel
2025-03-08 13:25:21 -07:00
parent b48a79bd64
commit 7e49811efb
12 changed files with 117 additions and 54 deletions
@@ -1,20 +1,56 @@
package com.adityachandel.booklore.config.security;
import com.adityachandel.booklore.exception.ApiError;
import com.adityachandel.booklore.model.dto.BookLoreUser;
import com.adityachandel.booklore.model.entity.EpubViewerPreferencesEntity;
import com.adityachandel.booklore.repository.PdfViewerPreferencesRepository;
import com.adityachandel.booklore.model.dto.request.UserLoginRequest;
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
import com.adityachandel.booklore.repository.UserRepository;
import lombok.AllArgsConstructor;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.Map;
@AllArgsConstructor
@Service
public class AuthenticationService {
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
private final JwtUtils jwtUtils;
public BookLoreUser getAuthenticatedUser() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return (BookLoreUser) authentication.getPrincipal();
}
public ResponseEntity<Map<String, String>> loginUser(UserLoginRequest loginRequest) {
BookLoreUserEntity user = userRepository.findByUsername(loginRequest.getUsername()).orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(loginRequest.getUsername()));
if (!passwordEncoder.matches(loginRequest.getPassword(), user.getPasswordHash())) {
throw ApiError.INVALID_CREDENTIALS.createException();
}
String accessToken = jwtUtils.generateAccessToken(user);
String refreshToken = jwtUtils.generateRefreshToken(user);
return ResponseEntity.ok(Map.of("accessToken", accessToken, "refreshToken", refreshToken));
}
public ResponseEntity<Map<String, String>> refreshToken(String refreshToken) {
if (!jwtUtils.validateToken(refreshToken)) {
throw ApiError.INVALID_CREDENTIALS.createException();
}
String username = jwtUtils.extractUsername(refreshToken);
BookLoreUserEntity user = userRepository.findByUsername(username).orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(username));
String newAccessToken = jwtUtils.generateAccessToken(user);
String newRefreshToken = jwtUtils.generateRefreshToken(user);
return ResponseEntity.ok(Map.of("accessToken", newAccessToken, "refreshToken", newRefreshToken));
}
}
@@ -3,42 +3,58 @@ package com.adityachandel.booklore.config.security;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Component
public class JwtUtils {
private final String secretKey = "G6u4m3g7M/b93k7m9a1h1Kw4l3D+5WqXldpl4nTjl4s=";
@Value("${security.jwt.secret}")
private String secretKey;
@Value("${security.jwt.expiration}")
private long accessTokenExpirationMs;
@Value("${security.jwt.refreshExpiration}")
private long refreshTokenExpirationMs;
private SecretKey getSigningKey() {
return Keys.hmacShaKeyFor(secretKey.getBytes(StandardCharsets.UTF_8));
}
public String generateToken(BookLoreUserEntity user) {
SecretKey key = getSigningKey();
Date now = new Date();
Date expirationDate = new Date(now.getTime() + 1000 * 60 * 60 * 10);
public String generateToken(BookLoreUserEntity user, boolean isRefreshToken) {
long expirationTime = isRefreshToken ? refreshTokenExpirationMs : accessTokenExpirationMs;
return Jwts.builder()
.subject(user.getUsername())
.claim("userId", user.getId())
.issuedAt(now)
.expiration(expirationDate)
.signWith(key, Jwts.SIG.HS256)
.issuedAt(new Date())
.expiration(new Date(System.currentTimeMillis() + expirationTime))
.signWith(getSigningKey(), Jwts.SIG.HS256)
.compact();
}
public String generateAccessToken(BookLoreUserEntity user) {
return generateToken(user, false);
}
public String generateRefreshToken(BookLoreUserEntity user) {
return generateToken(user, true);
}
public boolean validateToken(String token) {
try {
return !isTokenExpired(token);
extractClaims(token);
return true;
} catch (ExpiredJwtException e) {
System.out.println("Token expired: " + e.getMessage());
} catch (JwtException e) {
return false;
System.out.println("Invalid token: " + e.getMessage());
}
return false;
}
public Claims extractClaims(String token) {
@@ -55,15 +71,13 @@ public class JwtUtils {
public Long extractUserId(String token) {
Object userIdClaim = extractClaims(token).get("userId");
if (userIdClaim instanceof Integer) {
return ((Integer) userIdClaim).longValue();
} else if (userIdClaim instanceof Long) {
return (Long) userIdClaim;
if (userIdClaim instanceof Number) {
return ((Number) userIdClaim).longValue();
}
throw new IllegalArgumentException("userId claim is not of type Long or Integer");
throw new IllegalArgumentException("Invalid userId claim type");
}
private boolean isTokenExpired(String token) {
public boolean isTokenExpired(String token) {
return extractClaims(token).getExpiration().before(new Date());
}
}
@@ -1,9 +1,10 @@
package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.config.security.AuthenticationService;
import com.adityachandel.booklore.model.dto.UserCreateRequest;
import com.adityachandel.booklore.model.dto.request.RefreshTokenRequest;
import com.adityachandel.booklore.model.dto.request.UserLoginRequest;
import com.adityachandel.booklore.service.user.UserCreatorService;
import com.adityachandel.booklore.service.user.UserService;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
@@ -18,10 +19,10 @@ import java.util.Map;
@AllArgsConstructor
@RestController
@RequestMapping("/api/v1/auth")
public class AuthController {
public class AuthenticationController {
private final UserCreatorService userCreatorService;
private final UserService userService;
private final AuthenticationService authenticationService;
@PostMapping("/register")
@PreAuthorize("@securityUtil.isAdmin()")
@@ -32,6 +33,11 @@ public class AuthController {
@PostMapping("/login")
public ResponseEntity<Map<String, String>> loginUser(@RequestBody @Valid UserLoginRequest loginRequest) {
return userService.loginUser(loginRequest);
return authenticationService.loginUser(loginRequest);
}
@PostMapping("/refresh")
public ResponseEntity<Map<String, String>> refreshToken(@Valid @RequestBody RefreshTokenRequest request) {
return authenticationService.refreshToken(request.getRefreshToken());
}
}
@@ -0,0 +1,15 @@
package com.adityachandel.booklore.model.dto.request;
import jakarta.validation.constraints.NotBlank;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
public class RefreshTokenRequest {
@NotBlank(message = "Refresh token must not be blank")
private String refreshToken;
}
@@ -29,22 +29,9 @@ public class UserService {
private final UserRepository userRepository;
private final BookLoreUserMapper bookLoreUserMapper;
private final PasswordEncoder passwordEncoder;
private final LibraryRepository libraryRepository;
private final JwtUtils jwtUtils;
private final AuthenticationService authenticationService;
public ResponseEntity<Map<String, String>> loginUser(UserLoginRequest loginRequest) {
BookLoreUserEntity user = userRepository.findByUsername(loginRequest.getUsername()).orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(loginRequest.getUsername()));
if (!passwordEncoder.matches(loginRequest.getPassword(), user.getPasswordHash())) {
throw ApiError.INVALID_CREDENTIALS.createException();
}
String token = jwtUtils.generateToken(user);
return ResponseEntity.ok(Map.of("token", token));
}
public List<BookLoreUser> getBookLoreUsers() {
return userRepository.findAll()
.stream()
@@ -2,6 +2,12 @@ app:
path-book: '/app/books'
path-config: '/app/config'
security:
jwt:
secret: G6u4m3g7M/b93k7m9a1h1Kw4l3D+5WqXldpl4nTjl4s=
expiration: 36000000 # 10 hours in milliseconds
refreshExpiration: 604800000 # 7 days in milliseconds
spring:
servlet:
multipart: