diff --git a/waltid-libraries/auth/waltid-ktor-authnz/src/main/kotlin/id/walt/ktorauthnz/tokens/jwttoken/JwtTokenHandler.kt b/waltid-libraries/auth/waltid-ktor-authnz/src/main/kotlin/id/walt/ktorauthnz/tokens/jwttoken/JwtTokenHandler.kt index 72f897c5b..e94755671 100644 --- a/waltid-libraries/auth/waltid-ktor-authnz/src/main/kotlin/id/walt/ktorauthnz/tokens/jwttoken/JwtTokenHandler.kt +++ b/waltid-libraries/auth/waltid-ktor-authnz/src/main/kotlin/id/walt/ktorauthnz/tokens/jwttoken/JwtTokenHandler.kt @@ -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 { @@ -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 }