jjwt (JWT, JSON Web Tokens) [Kotlin]


jwtk/jjwt is a libraries for creating and verifying JSON Web Tokens (JWT) on Java / Kotlin.

I would like to show some introduction for jjwt on Kotlin.

🗽 Installation

Add version information to gradle.properties:

# JWT
jjwtVersion=0.10.6

Define the following dependencies to build.gradle.kts :

val jjwtVersion: String by project
implementation("io.jsonwebtoken:jjwt-api:$jjwtVersion")
implementation("io.jsonwebtoken:jjwt-impl:$jjwtVersion")
implementation("io.jsonwebtoken:jjwt-jackson:$jjwtVersion")

👽 Generate sample jwt string

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import java.security.Key;

// We need a signing key, so we'll create one just for this example. Usually
// the key would be read from your application configuration instead.
val signingKey = Keys.secretKeyFor(SignatureAlgorithm.HS512)

// Generate JWT String
val exampleJwt = Jwts.builder().setSubject("Joe").signWith(signingKey).compact()
System.out.println("exampleJwt: $exampleJwt")
// => exampleJwt: eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJKb2UifQ.EzFGmEj9KG9zrNsMBc0Y2YoUVuQJHL45uLrWFfj5CTBasArXAI-IEf_A0jYTKBZNhwLz3-NWEekPf8tll4yJVQ

// Verify JWT String
val claims = Jwts.parser().setSigningKey(signingKey).parseClaimsJws(exampleJwt).body
System.out.println("Decode result: $claims")
// => Decode result: {sub=Joe}

🎂 Generate JWT with original Key

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import java.security.Key;

var keyStr = "DummyKeyStringDummyKeyStringDummyKeyStringDummyKeyStringDummyKeyStringDummyKeyString"
val key = Keys.hmacShaKeyFor(keyStr.toByteArray())

val jwt = Jwts.builder().claim("userId", 1).signWith(key).compact()
// => example2Jwt: eyJhbGciOiJIUzUxMiJ9.eyJ1c2VySWQiOjF9.VApKjgGHRqTB-LZaYw33kf0ovTjgpCb153HRxQCfiYBQGfLwu0fSsRQHv4dAeCm33YNxAgLJ5doi6G2bCIBS5A

System.out.println("example2Jwt: $jwt")
val claims = Jwts.parser()
.setSigningKey(key)
.parseClaimsJws(jwt)
System.out.println("Decode result: $claims userId: ${claims.body["userId"]}")
// => Decode result: header={alg=HS512},body={userId=1},signature=VApKjgGHRqTB-LZaYw33kf0ovTjgpCb153HRxQCfiYBQGfLwu0fSsRQHv4dAeCm33YNxAgLJ5doi6G2bCIBS5A userId: 1

🍄 Special Thanks

🖥 Recommended VPS Service

VULTR provides high performance cloud compute environment for you. Vultr has 15 data-centers strategically placed around the globe, you can use a VPS with 512 MB memory for just $ 2.5 / month ($ 0.004 / hour). In addition, Vultr is up to 4 times faster than the competition, so please check it => Check Benchmark Results!!