From 975ebae553465398091b00377cf8790c80ea7547 Mon Sep 17 00:00:00 2001 From: FyloZ Date: Fri, 27 Aug 2021 18:44:16 -0400 Subject: [PATCH] #12 Add custom claims to JWT builder --- .../fyloz/colorrecipesexplorer/utils/Jwt.kt | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Jwt.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Jwt.kt index a430fb3..b36527e 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Jwt.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Jwt.kt @@ -12,11 +12,14 @@ data class Jwt( val subject: String, val secret: String, val duration: Long? = null, - val signatureAlgorithm: SignatureAlgorithm = SignatureAlgorithm.HS512 + val signatureAlgorithm: SignatureAlgorithm = SignatureAlgorithm.HS512, + val claims: Map = mapOf() ) { val token: String by lazy { val builder = Jwts.builder() + .signWith(keyFromSecret(secret)) .setSubject(subject) + .addClaims(claims.filterValues { it != null }) duration?.let { val expirationMs = System.currentTimeMillis() + it @@ -25,15 +28,21 @@ data class Jwt( builder.setExpiration(expirationDate) } - builder - .signWith(keyFromSecret(secret)) - .compact() + builder.compact() } } /** Build a [Jwt] for the given [User]. */ fun User.buildJwt(secret: String, duration: Long?) = - Jwt(this.id.toString(), secret, duration) + Jwt( + subject = this.id.toString(), + secret, + duration, + claims = mapOf( + "groupId" to this.group?.id, + "groupName" to this.group?.name + ) + ) /** Parses the given [jwt] string. */ fun parseJwt(jwt: String, secret: String) =