Skip to content

Commit

Permalink
Check JWT token expiration
Browse files Browse the repository at this point in the history
  • Loading branch information
waltkb committed Nov 19, 2024
1 parent 96ff3f6 commit 4d71df7
Showing 1 changed file with 14 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ import id.walt.crypto.keys.Key
import id.walt.crypto.utils.JwsUtils.decodeJws
import id.walt.ktorauthnz.sessions.AuthSession
import id.walt.ktorauthnz.tokens.TokenHandler
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.put
import kotlinx.datetime.Clock
import kotlinx.datetime.Instant
import kotlinx.serialization.json.*

class JwtTokenHandler : TokenHandler {

Expand All @@ -23,7 +23,18 @@ class JwtTokenHandler : TokenHandler {
return signingKey.signJws(payload)
}

/** Check JWT `exp` if in token */
fun checkExpirationIfExists(jwtPayload: JsonObject) {
jwtPayload["exp"]?.jsonPrimitive?.long?.let { exp ->
val expirationDate = Instant.fromEpochSeconds(exp)
val now = Clock.System.now()
check(now < expirationDate) { "JWT Token expired since: ${now - expirationDate}" }
}
}

override suspend fun validateToken(token: String): Boolean {
checkExpirationIfExists(token.decodeJws().payload)

return verificationKey.verifyJws(token).isSuccess
}

Expand Down

0 comments on commit 4d71df7

Please sign in to comment.