fix: update JwtService to handle default expiration and add tests for token generation
All checks were successful
Build And Publish Production Image / Build And Publish Production Image (push) Successful in 39s
All checks were successful
Build And Publish Production Image / Build And Publish Production Image (push) Successful in 39s
This commit is contained in:
@@ -14,8 +14,10 @@ import java.util.Date
|
||||
@Service
|
||||
class JwtService(
|
||||
@Value("\${app.jwt.secret}") val secret: String,
|
||||
@Value("\${app.jwt.expiration-ms}") val expirationMs: Long
|
||||
@Value("\${app.jwt.expiration-ms:86400000}") expirationMsRaw: String
|
||||
) {
|
||||
private val expirationMs: Long = expirationMsRaw.toLongOrNull() ?: 86400000L
|
||||
|
||||
private val signingKey by lazy {
|
||||
Keys.hmacShaKeyFor(secret.toByteArray(Charsets.UTF_8))
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@ class AuthServiceTest {
|
||||
fun should_returnValidClaims_when_jwtTokenParsed() {
|
||||
val realJwtService = JwtService(
|
||||
secret = "test-secret-key-for-testing-only-must-be-at-least-32-characters",
|
||||
expirationMs = 86400000L
|
||||
expirationMsRaw = "86400000"
|
||||
)
|
||||
val token = realJwtService.generateToken()
|
||||
|
||||
@@ -51,7 +51,7 @@ class AuthServiceTest {
|
||||
fun should_returnFalse_when_expiredTokenValidated() {
|
||||
val realJwtService = JwtService(
|
||||
secret = "test-secret-key-for-testing-only-must-be-at-least-32-characters",
|
||||
expirationMs = 1L
|
||||
expirationMsRaw = "1"
|
||||
)
|
||||
val token = realJwtService.generateToken()
|
||||
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.condado.newsletter.service
|
||||
|
||||
import io.jsonwebtoken.Jwts
|
||||
import io.jsonwebtoken.security.Keys
|
||||
import org.junit.jupiter.api.Assertions.assertTrue
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
class JwtServiceTest {
|
||||
|
||||
private val secret = "12345678901234567890123456789012"
|
||||
|
||||
@Test
|
||||
fun should_generate_token_when_expiration_is_empty() {
|
||||
val jwtService = JwtService(secret, "")
|
||||
|
||||
val token = jwtService.generateToken()
|
||||
|
||||
val claims = Jwts.parser()
|
||||
.verifyWith(Keys.hmacShaKeyFor(secret.toByteArray(Charsets.UTF_8)))
|
||||
.build()
|
||||
.parseSignedClaims(token)
|
||||
.payload
|
||||
|
||||
assertTrue(claims.expiration.after(claims.issuedAt))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user