Generate and sign a JWT token

Hello all,

I’m having difficulties generating a signed JWT token using the jjwt library.

My code:

import io.jsonwebtoken.Jwts
import org.junit.Assert.assertTrue
import org.junit.Test
import java.util.Date

class JwtTest {
    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")
            .setExpiration(Date(now.time + 2 * 1000 * 60 * 60))

        println("token: $jwt")


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 {
    fun generate() {
        val accessKey = "auzNN7V0aB30poSilNi15HCiE"

        val signer: Signer = HMACSigner.newSHA256Signer(accessKey)

        val jwt = JWT()
            .addClaim("data", "flow")

        val token = JWT.getEncoder().encode(jwt, signer)

        println("token: $token")


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.