728x90
        // Generate JWT token
        return Jwts.builder()
                .setSubject(user.getUserId())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + 86400000)) // 24 hours expiration
                .signWith(SignatureAlgorithm.HS512, "YourSecretKey") // Replace 'YourSecretKey' with your actual secret key
                .compact();

 

 

io.jsonwebtoken library 안에서 signWith (SignatureAlgorithm, String) 라는 놈은 이제 Deprecated 된 놈 중 하나인데 보안적인 이유때문에 짜진 친구이다.

 

이제는 String 대신에 Key 하나를 던져서 보안성을 강화해보자

 

 

Key 를 사용하기 위해 Library 2개를 더 납치해준다

import javax.crypto.SecretKey;
import io.jsonwebtoken.security.Keys;
@Service
public class AuthService {

    @Autowired
    private UserRepository userRepository;

    private final SecretKey key = Keys.secretKeyFor(SignatureAlgorithm.HS512); // Securely generate a key

    public String authenticateAndGenerateToken(LoginDto loginDto) {
        User user = userRepository.findByUserId(loginDto.getUserId());

        if (user == null || !new BCryptPasswordEncoder().matches(loginDto.getPassword(), user.getPassword())) {
            throw new IllegalArgumentException("Invalid credentials");
        }

        return Jwts.builder()
                .setSubject(user.getUserId())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + 86400000)) // 24 hours expiration
                .signWith(key, SignatureAlgorithm.HS512)
                .compact();
    }
}

 

 

+ Recent posts