Hello all,
I’m having difficulties generating a signed JWT token using the jjwt library.
My code:
import io.jsonwebtoken.Jwts
import io.jsonwebtoken.io.Encoders
import io.jsonwebtoken.security.Keys
import org.junit.Assert.assertTrue
import org.junit.Test
import java.util.Date
class JwtTest {
@Test
fun generate() {
val accessKey = "auzNN7V0aB30poSilNi15HCiE"
val key = Keys.hmacShaKeyFor(Encoders.BASE64.encode(accessKey.toByteArray()).toByteArray())
val now = Date()
val jwt = Jwts.builder()
.setHeaderParam("typ", "JWT")
.claim("data", "flow")
.setIssuedAt(now)
.setExpiration(Date(now.time + 2 * 1000 * 60 * 60))
.signWith(key)
.compact()
println("token: $jwt")
assertTrue(jwt.isNotEmpty())
}
}
It cannot be verified according to this tool.
Any ideas what I’m doing wrong with the signing?
I gave up with the other library and I am using this one instead (Note for Android users it is only available for API 26 onwards).
My working example:
import io.fusionauth.jwt.Signer
import io.fusionauth.jwt.domain.JWT
import io.fusionauth.jwt.hmac.HMACSigner
import org.junit.Assert.assertTrue
import org.junit.Test
import java.time.ZoneOffset
import java.time.ZonedDateTime
class JwtTest {
@Test
fun generate() {
val accessKey = "auzNN7V0aB30poSilNi15HCiE"
val signer: Signer = HMACSigner.newSHA256Signer(accessKey)
val jwt = JWT()
.addClaim("data", "flow")
.setIssuedAt(ZonedDateTime.now(ZoneOffset.UTC))
.setExpiration(ZonedDateTime.now(ZoneOffset.UTC).plusHours(2))
val token = JWT.getEncoder().encode(jwt, signer)
println("token: $token")
assertTrue(token.isNotEmpty())
}
}
While it’s great that you found a different library that works for you, this forum might not be the best place to ask for help with libraries. Unless the library is maintained by the kotlin team or isn’t used by many of the active people here there is only a small chance that someone here can help you.
Maybe a better place to start looking for help is the jjwt issue page on github, especially since there isn’t an obvious mistake in your code.
1 Like
I disagree. This can be a good reference point for future Kotlin developers looking to use JWT in Kotlin.
The support forum description says:
If you need help getting things done in Kotlin, ask here.
My question satisfies this part and I’m very happy to help future questions from fellow developers on this topic.
I wasn’t trying to say that this forum is the wrong place to ask. I just meant that library specific questions you will often have more luck asking the library authors directly if no one here is able to help you. This forum is still a good place to start.