47 lines
1.4 KiB
Kotlin
47 lines
1.4 KiB
Kotlin
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
|
|
}
|
|
}
|