JWT Tokens in Kotlin: Complete Guide for Developers
JSON Web Token (JWT) is a compact, URL-safe format for transmitting claims between two parties. In the Kotlin ecosystem, JWT is widely used for authentication, authorization, and data exchange in microservices, mobile applications, and web applications built with Ktor or Spring Boot. In this article, we will cover how to create, sign, and verify JWT tokens in Kotlin using popular libraries: JJWT (Java JWT) and Auth0 java-jwt.
What is JWT and Why is it Needed in Kotlin?
JWT consists of three parts: header, payload, and signature. In Kotlin, JWT tokens allow you to:
- Implement stateless authentication (the server does not store sessions).
- Transmit roles and access rights (claims).
- Work with distributed systems and APIs.
- Integrate with OAuth2 and OpenID Connect.
Installing Libraries for Working with JWT in Kotlin
For Kotlin/JVM projects, two libraries are best suited: io.jsonwebtoken:jjwt (JJWT) and com.auth0:java-jwt. Add the dependencies to build.gradle.kts:
// build.gradle.ktsdependencies { // JJWT (recommended) implementation("io.jsonwebtoken:jjwt-api:0.12.6") runtimeOnly("io.jsonwebtoken:jjwt-impl:0.12.6") runtimeOnly("io.jsonwebtoken:jjwt-jackson:0.12.6") // for JSON
// Auth0 java-jwt implementation("com.auth0:java-jwt:4.4.0")}Creating a JWT Token Using JJWT (Kotlin)
JJWT provides a clean fluent API. Below is an example of creating a token with HMAC-SHA256 signing:
import io.jsonwebtoken.Jwtsimport io.jsonwebtoken.SignatureAlgorithmimport io.jsonwebtoken.security.Keysimport java.util.Date
fun createJwtToken(userId: String, role: String): String { val secretKey = Keys.hmacShaKeyFor("my_secret_key_32_bytes_long!!".toByteArray())
val token = Jwts.builder() .setSubject(userId) .claim("role", role) .setIssuedAt(Date()) .setExpiration(Date(System.currentTimeMillis() + 3600_000)) // 1 hour .signWith(secretKey, SignatureAlgorithm.HS256) .compact()
return token}Validating and Parsing a JWT Token
To validate the token, use Jwts.parserBuilder(). Example of validation with claim extraction:
import io.jsonwebtoken.Jwtsimport io.jsonwebtoken.security.Keys
fun validateToken(token: String): Map<String, Any>? { return try { val secretKey = Keys.hmacShaKeyFor("my_secret_key_32_bytes_long!!".toByteArray()) val claims = Jwts.parserBuilder() .setSigningKey(secretKey) .build() .parseClaimsJws(token) .body
claims } catch (e: Exception) { println("Invalid token: ${e.message}") null }}Working with JWT via Auth0 java-jwt (Kotlin)
The Auth0 library is also popular. Example of creating and verifying a token with RSA signing:
import com.auth0.jwt.JWTimport com.auth0.jwt.algorithms.Algorithmimport com.auth0.jwt.interfaces.DecodedJWTimport java.security.interfaces.RSAPrivateKeyimport java.security.interfaces.RSAPublicKeyimport java.util.Date
// Token generationfun createRsaToken(userId: String, privateKey: RSAPrivateKey): String { val algorithm = Algorithm.RSA256(null, privateKey) return JWT.create() .withSubject(userId) .withIssuer("auth0") .withExpiresAt(Date(System.currentTimeMillis() + 3600_000)) .sign(algorithm)}
// Token verificationfun verifyRsaToken(token: String, publicKey: RSAPublicKey): DecodedJWT? { return try { val algorithm = Algorithm.RSA256(publicKe Also in library
Juniper: Creating Efficient GraphQL APIs in Rust
Monitoring TypeScript Applications: Libraries, Tools, and Setup
Geolocation and Maps in PHP: Overview of Libraries and Tools
Caching in PHP: Redis, Memcached, APCu, and File Caching