feat(backend): implement step 10 — JWT authentication (JwtService, AuthService, AuthController, JwtAuthFilter, SecurityConfig)

This commit is contained in:
2026-03-26 19:08:09 -03:00
parent 9065db504e
commit 031ad3d4b2
9 changed files with 243 additions and 138 deletions

View File

@@ -0,0 +1,46 @@
package com.condado.newsletter.service
import io.jsonwebtoken.ExpiredJwtException
import io.jsonwebtoken.Jwts
import io.jsonwebtoken.security.Keys
import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Service
import java.util.Date
/**
* Handles JWT token creation and validation using JJWT 0.12.x.
* The secret and expiration are read from environment variables.
*/
@Service
class JwtService(
@Value("\${app.jwt.secret}") val secret: String,
@Value("\${app.jwt.expiration-ms}") val expirationMs: Long
) {
private val signingKey by lazy {
Keys.hmacShaKeyFor(secret.toByteArray(Charsets.UTF_8))
}
/** Generates a new signed JWT token valid for [expirationMs] milliseconds. */
fun generateToken(): String {
val now = Date()
return Jwts.builder()
.subject("admin")
.issuedAt(now)
.expiration(Date(now.time + expirationMs))
.signWith(signingKey)
.compact()
}
/**
* Validates a JWT token.
* @return `true` if the token is valid and not expired; `false` otherwise.
*/
fun validateToken(token: String): Boolean = try {
Jwts.parser().verifyWith(signingKey).build().parseSignedClaims(token)
true
} catch (e: ExpiredJwtException) {
false
} catch (e: Exception) {
false
}
}