refactor(security): replace JWT library with Nimbus JOSE and improve token validation (#911)

Co-authored-by: James Ward <james@notjam.es>
This commit is contained in:
brios
2026-04-29 22:14:19 +00:00
committed by GitHub
co-authored by James Ward
parent bac714eb61
commit 491df479a4
3 changed files with 148 additions and 53 deletions
+1 -6
View File
@@ -100,7 +100,7 @@ dependencies {
implementation("org.springframework.boot:spring-boot-configuration-processor") implementation("org.springframework.boot:spring-boot-configuration-processor")
implementation("org.springframework.boot:spring-boot-starter-security") implementation("org.springframework.boot:spring-boot-starter-security")
implementation("org.springframework.boot:spring-boot-starter-mail") implementation("org.springframework.boot:spring-boot-starter-mail")
implementation("org.springframework.boot:spring-boot-starter-oauth2-client") implementation("com.nimbusds:nimbus-jose-jwt:10.9")
// --- Reactive Streams --- // --- Reactive Streams ---
implementation("io.projectreactor:reactor-core") implementation("io.projectreactor:reactor-core")
@@ -110,11 +110,6 @@ dependencies {
implementation("org.springframework.boot:spring-boot-starter-flyway") implementation("org.springframework.boot:spring-boot-starter-flyway")
implementation("org.flywaydb:flyway-mysql:12.4.0") implementation("org.flywaydb:flyway-mysql:12.4.0")
// --- Security & Authentication ---
implementation("io.jsonwebtoken:jjwt-api:0.13.0")
runtimeOnly("io.jsonwebtoken:jjwt-impl:0.13.0")
runtimeOnly("io.jsonwebtoken:jjwt-jackson:0.13.0")
// --- Lombok (For Clean Code) --- // --- Lombok (For Clean Code) ---
compileOnly("org.projectlombok:lombok:1.18.46") compileOnly("org.projectlombok:lombok:1.18.46")
annotationProcessor("org.projectlombok:lombok:1.18.46") annotationProcessor("org.projectlombok:lombok:1.18.46")
@@ -1,52 +1,103 @@
package org.booklore.config.security; package org.booklore.config.security;
import org.booklore.model.entity.BookLoreUserEntity; import com.nimbusds.jose.JWSAlgorithm;
import org.booklore.service.security.JwtSecretService; import com.nimbusds.jose.JWSHeader;
import io.jsonwebtoken.Claims; import com.nimbusds.jose.JWSSigner;
import io.jsonwebtoken.ExpiredJwtException; import com.nimbusds.jose.JWSVerifier;
import io.jsonwebtoken.JwtException; import com.nimbusds.jose.KeyLengthException;
import io.jsonwebtoken.Jwts; import com.nimbusds.jose.crypto.MACSigner;
import io.jsonwebtoken.security.Keys; import com.nimbusds.jose.crypto.MACVerifier;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;
import com.nimbusds.jwt.proc.BadJWTException;
import com.nimbusds.jwt.proc.DefaultJWTClaimsVerifier;
import jakarta.annotation.PostConstruct;
import lombok.Getter; import lombok.Getter;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.booklore.exception.ApiError;
import org.booklore.model.entity.BookLoreUserEntity;
import org.booklore.service.security.JwtSecretService;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.time.Instant; import java.time.Instant;
import java.util.Date; import java.util.Date;
import java.util.Set;
@Slf4j @Slf4j
@Service
@Component @Component
@RequiredArgsConstructor @RequiredArgsConstructor
public class JwtUtils { public class JwtUtils {
private final JwtSecretService jwtSecretService; private final JwtSecretService jwtSecretService;
private static final int MIN_SECRET_BYTES = 32;
private static final String JWT_ISSUER = "booklore";
private DefaultJWTClaimsVerifier<?> claimsVerifier;
@Getter @Getter
public static final long accessTokenExpirationMs = 1000L * 60 * 60 * 2; // 2 hours public static final long accessTokenExpirationMs = 1000L * 60 * 60 * 2; // 2 hours
@Getter @Getter
public static final long refreshTokenExpirationMs = 1000L * 60 * 60 * 24 * 30; // 30 days public static final long refreshTokenExpirationMs = 1000L * 60 * 60 * 24 * 30; // 30 days
private SecretKey getSigningKey() { @PostConstruct
String secretKey = jwtSecretService.getSecret(); public void init() {
return Keys.hmacShaKeyFor(secretKey.getBytes(StandardCharsets.UTF_8)); validateSecret();
this.claimsVerifier = new DefaultJWTClaimsVerifier<>(
new JWTClaimsSet.Builder().issuer(JWT_ISSUER).build(),
Set.of("exp", "iat", "iss", "sub", "userId")
);
}
public void validateSecret() {
try {
getSecretBytes();
} catch (IllegalStateException e) {
// Misconfiguration — fail fast.
throw e;
} catch (DataAccessException e) {
// DB not ready yet; will be re-validated on first use.
log.warn("Could not validate JWT secret at startup (database not ready), will validate on first use: {}", e.getMessage());
}
}
private byte[] getSecretBytes() {
byte[] key = jwtSecretService.getSecret().getBytes(StandardCharsets.UTF_8);
if (key.length < MIN_SECRET_BYTES) {
throw new IllegalStateException("JWT secret must be at least " + MIN_SECRET_BYTES + " bytes for HS256");
}
return key;
} }
public String generateToken(BookLoreUserEntity user, boolean isRefreshToken) { public String generateToken(BookLoreUserEntity user, boolean isRefreshToken) {
long expirationTime = isRefreshToken ? refreshTokenExpirationMs : accessTokenExpirationMs; long expirationTime = isRefreshToken ? refreshTokenExpirationMs : accessTokenExpirationMs;
Instant now = Instant.now(); Instant now = Instant.now();
return Jwts.builder()
.issuer("booklore") try {
.subject(user.getUsername()) JWSSigner signer = new MACSigner(getSecretBytes());
.claim("userId", user.getId())
.claim("isDefaultPassword", user.isDefaultPassword()) JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
.issuedAt(Date.from(now)) .issuer(JWT_ISSUER)
.expiration(Date.from(now.plusMillis(expirationTime))) .subject(user.getUsername())
.signWith(getSigningKey(), Jwts.SIG.HS256) .claim("userId", user.getId())
.compact(); .claim("isDefaultPassword", user.isDefaultPassword())
.issueTime(Date.from(now))
.expirationTime(Date.from(now.plusMillis(expirationTime)))
.build();
SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.HS256), claimsSet);
signedJWT.sign(signer);
return signedJWT.serialize();
} catch (KeyLengthException e) {
log.error("JWT secret is too short: {}", e.getMessage());
throw new IllegalStateException("JWT secret must be at least " + MIN_SECRET_BYTES + " bytes for HS256", e);
} catch (Exception e) {
log.error("Error generating JWT token", e);
throw new RuntimeException("Could not generate token", e);
}
} }
public String generateAccessToken(BookLoreUserEntity user) { public String generateAccessToken(BookLoreUserEntity user) {
@@ -57,45 +108,93 @@ public class JwtUtils {
return generateToken(user, true); return generateToken(user, true);
} }
/**
* Parses and verifies the JWT token signature.
* Does NOT check for expiration or other claims.
*/
private SignedJWT parseAndVerify(String token) throws Exception {
SignedJWT signedJWT;
try {
signedJWT = SignedJWT.parse(token);
} catch (Exception e) {
log.error("Malformed token", e);
throw ApiError.JWT_INVALID.createException("Malformed token");
}
JWSVerifier verifier = new MACVerifier(getSecretBytes());
if (!signedJWT.verify(verifier)) {
throw ApiError.JWT_INVALID.createException("Invalid token signature");
}
return signedJWT;
}
/**
* Validates the token's signature, expiration, and issuer.
*/
public boolean validateToken(String token) { public boolean validateToken(String token) {
try { try {
extractClaims(token); SignedJWT signedJWT = parseAndVerify(token);
JWTClaimsSet claims = signedJWT.getJWTClaimsSet();
validateClaims(claims);
return true; return true;
} catch (ExpiredJwtException e) { } catch (Exception e) {
log.debug("Token expired: {}", e.getMessage());
} catch (JwtException e) {
log.debug("Invalid token: {}", e.getMessage()); log.debug("Invalid token: {}", e.getMessage());
return false;
} }
return false;
} }
public Claims extractClaims(String token) { /**
Claims claims = Jwts.parser() * Checks if claims are valid using the built-in Nimbus verifier (expiration, issuer, clock skew).
.verifyWith(getSigningKey()) * @throws BadJWTException if claims are invalid.
.build() */
.parseSignedClaims(token) private void validateClaims(JWTClaimsSet claims) throws BadJWTException {
.getPayload(); claimsVerifier.verify(claims, null);
Object userId = claims.getClaim("userId");
// Graceful issuer enforcement: reject tokens with a wrong issuer, if (!(userId instanceof Number)) {
// but allow legacy tokens that have no issuer claim (issued before this check). throw new BadJWTException("Invalid userId claim type");
// After a full token rotation cycle (~30 days), switch to hard .requireIssuer().
String issuer = claims.getIssuer();
if (issuer != null && !"booklore".equals(issuer)) {
throw new JwtException("Invalid issuer: " + issuer);
} }
return claims;
} }
/**
* Extracts claims from a token after verifying signature and validating expiration/issuer.
* @throws RuntimeException if token is invalid or expired.
*/
public JWTClaimsSet extractClaims(String token) {
try {
SignedJWT signedJWT = parseAndVerify(token);
JWTClaimsSet claims = signedJWT.getJWTClaimsSet();
validateClaims(claims);
return claims;
} catch (BadJWTException e) {
throw ApiError.JWT_INVALID.createException(e.getMessage());
} catch (Exception e) {
if (e instanceof RuntimeException re) throw re;
throw ApiError.JWT_INVALID.createException(e.getMessage());
}
}
/**
* Extracts username from token.
* @throws RuntimeException if token is invalid or expired.
*/
public String extractUsername(String token) { public String extractUsername(String token) {
return extractClaims(token).getSubject(); try {
return extractClaims(token).getSubject();
} catch (Exception e) {
log.warn("Failed to extract username from token: {}", e.getMessage());
throw e;
}
} }
/**
* Extracts user ID from token.
* @throws RuntimeException if token is invalid or expired.
*/
public Long extractUserId(String token) { public Long extractUserId(String token) {
Object userIdClaim = extractClaims(token).get("userId"); Object userIdClaim = extractClaims(token).getClaim("userId");
if (userIdClaim instanceof Number) { if (userIdClaim instanceof Number) {
return ((Number) userIdClaim).longValue(); return ((Number) userIdClaim).longValue();
} }
throw new IllegalArgumentException("Invalid userId claim type"); throw ApiError.JWT_INVALID.createException("Invalid userId claim type");
} }
} }
@@ -73,7 +73,8 @@ public enum ApiError {
OIDC_INVALID_REDIRECT_URI(HttpStatus.BAD_REQUEST, "Invalid redirect URI"), OIDC_INVALID_REDIRECT_URI(HttpStatus.BAD_REQUEST, "Invalid redirect URI"),
OIDC_LOGOUT_REPLAY(HttpStatus.BAD_REQUEST, "Logout token has already been processed"), OIDC_LOGOUT_REPLAY(HttpStatus.BAD_REQUEST, "Logout token has already been processed"),
OIDC_LOGOUT_MISSING_JTI(HttpStatus.BAD_REQUEST, "Logout token missing required jti claim"), OIDC_LOGOUT_MISSING_JTI(HttpStatus.BAD_REQUEST, "Logout token missing required jti claim"),
OIDC_INVALID_STATE(HttpStatus.BAD_REQUEST, "Invalid or expired OIDC state parameter"); OIDC_INVALID_STATE(HttpStatus.BAD_REQUEST, "Invalid or expired OIDC state parameter"),
JWT_INVALID(HttpStatus.UNAUTHORIZED, "Invalid JWT token: %s");
private final HttpStatus status; private final HttpStatus status;
private final String message; private final String message;