#12 Add custom claims to JWT builder

This commit is contained in:
FyloZ 2021-08-27 18:44:16 -04:00
parent 4dfca3349c
commit 975ebae553
Signed by: william
GPG Key ID: 835378AE9AF4AE97
1 changed files with 14 additions and 5 deletions

View File

@ -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<String, Any?> = 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) =