Generate and store JWT secret in DB

This commit is contained in:
aditya.chandel
2025-03-08 16:25:17 -07:00
parent a562701c43
commit 7da452e4eb
6 changed files with 106 additions and 16 deletions
@@ -3,26 +3,27 @@ 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 com.adityachandel.booklore.service.JwtSecretService;
import org.springframework.stereotype.Component;
import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.nio.charset.StandardCharsets;
@Component
public class JwtUtils {
@Value("${security.jwt.secret}")
private String secretKey;
private final JwtSecretService jwtSecretService;
private final long accessTokenExpirationMs;
private final long refreshTokenExpirationMs;
@Value("${security.jwt.expiration}")
private long accessTokenExpirationMs;
@Value("${security.jwt.refreshExpiration}")
private long refreshTokenExpirationMs;
public JwtUtils(JwtSecretService jwtSecretService) {
this.jwtSecretService = jwtSecretService;
this.accessTokenExpirationMs = 36000000; // 10 hours
this.refreshTokenExpirationMs = 604800000; // 7 days
}
private SecretKey getSigningKey() {
String secretKey = jwtSecretService.getSecret();
return Keys.hmacShaKeyFor(secretKey.getBytes(StandardCharsets.UTF_8));
}
@@ -0,0 +1,29 @@
package com.adityachandel.booklore.model.entity;
import jakarta.persistence.*;
import lombok.*;
import java.time.LocalDateTime;
@Entity
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "jwt_secret")
public class JwtSecretEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String secret;
@Column(name = "created_at", updatable = false)
private LocalDateTime createdAt = LocalDateTime.now();
public JwtSecretEntity(String secret) {
this.secret = secret;
}
}
@@ -0,0 +1,15 @@
package com.adityachandel.booklore.repository;
import com.adityachandel.booklore.model.entity.JwtSecretEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface JwtSecretRepository extends JpaRepository<JwtSecretEntity, Long> {
@Query("SELECT s.secret FROM JwtSecretEntity s ORDER BY s.createdAt DESC LIMIT 1")
Optional<String> findLatestSecret();
}
@@ -0,0 +1,44 @@
package com.adityachandel.booklore.service;
import com.adityachandel.booklore.model.entity.JwtSecretEntity;
import com.adityachandel.booklore.repository.JwtSecretRepository;
import jakarta.annotation.PostConstruct;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.security.SecureRandom;
import java.util.Base64;
@Service
public class JwtSecretService {
private final JwtSecretRepository jwtSecretRepository;
private String cachedSecret;
public JwtSecretService(JwtSecretRepository jwtSecretRepository) {
this.jwtSecretRepository = jwtSecretRepository;
}
@PostConstruct
@Transactional
public void initializeSecret() {
cachedSecret = jwtSecretRepository.findLatestSecret().orElseGet(this::generateAndStoreNewSecret);
}
private String generateAndStoreNewSecret() {
String newSecret = generateRandomSecret();
JwtSecretEntity secretEntity = new JwtSecretEntity(newSecret);
jwtSecretRepository.save(secretEntity);
return newSecret;
}
private String generateRandomSecret() {
byte[] randomBytes = new byte[32];
new SecureRandom().nextBytes(randomBytes);
return Base64.getEncoder().encodeToString(randomBytes);
}
public String getSecret() {
return cachedSecret;
}
}
@@ -2,12 +2,6 @@ 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:
@@ -1,3 +1,10 @@
CREATE TABLE IF NOT EXISTS jwt_secret
(
id SERIAL PRIMARY KEY,
secret TEXT NOT NULL,
created_at TIMESTAMP DEFAULT NOW()
);
CREATE TABLE IF NOT EXISTS library
(
id BIGINT AUTO_INCREMENT PRIMARY KEY,