JWT
suggest changeJSON Web Token (JWT) is an open industry standard (RFC 7519) for securely transmitting claims between parties as a compact, URL-safe JSON object. In Kotlin backend systems (such as Ktor, Spring Boot, or Micronaut), JWTs are widely used for stateless authentication and authorization between mobile/web clients and microservices.
Installing java-jwt
The standard, battle-tested library for handling JWTs in Kotlin is Auth0's java-jwt:
// build.gradle.kts
dependencies {
implementation("com.auth0:java-jwt:4.6.2")
}
Generating and Signing a JWT
A JWT consists of three parts separated by dots (.): a header, a payload (claims), and a cryptographic signature.
Here is how to create a signed JWT using symmetric HMAC-SHA256:
import com.auth0.jwt.JWT
import com.auth0.jwt.algorithms.Algorithm
import java.time.Instant
import java.time.temporal.ChronoUnit
import java.util.Date
class JwtService(private val secret: String, private val issuer: String) {
private val algorithm = Algorithm.HMAC256(secret)
fun generateToken(userId: String, email: String, roles: List<String>): String {
val now = Instant.now()
val expiresAt = now.plus(2, ChronoUnit.HOURS)
return JWT.create()
.withIssuer(issuer)
.withSubject(userId)
.withAudience("https://api.example.com")
.withIssuedAt(Date.from(now))
.withExpiresAt(Date.from(expiresAt))
// Custom claims
.withClaim("email", email)
.withClaim("roles", roles)
.sign(algorithm)
}
}
fun main() {
val service = JwtService("super-secret-256-bit-key-string", "https://auth.example.com")
val token = service.generateToken("user_42", "alice@example.com", listOf("USER", "ADMIN"))
println("Generated JWT:")
println(token)
}
Verifying and Decoding Tokens
When a request arrives with an Authorization: Bearer <token> header, verify the cryptographic signature and claim constraints before trusting any payload data:
import com.auth0.jwt.JWT
import com.auth0.jwt.algorithms.Algorithm
import com.auth0.jwt.exceptions.JWTVerificationException
import com.auth0.jwt.exceptions.SignatureVerificationException
import com.auth0.jwt.exceptions.TokenExpiredException
import com.auth0.jwt.interfaces.DecodedJWT
data class AuthenticatedUser(val userId: String, val email: String, val roles: List<String>)
fun verifyAndDecodeToken(token: String, secret: String, issuer: String): AuthenticatedUser? {
val algorithm = Algorithm.HMAC256(secret)
val verifier = JWT.require(algorithm)
.withIssuer(issuer)
.withAudience("https://api.example.com")
.build()
return try {
val jwt: DecodedJWT = verifier.verify(token)
val userId = jwt.subject
val email = jwt.getClaim("email").asString()
val roles = jwt.getClaim("roles").asList(String::class.java) ?: emptyList()
AuthenticatedUser(userId, email, roles)
} catch (e: TokenExpiredException) {
println("Token expired at: ${e.expiredOn}")
null
} catch (e: SignatureVerificationException) {
println("Invalid token signature: ${e.message}")
null
} catch (e: JWTVerificationException) {
println("JWT verification failed: ${e.message}")
null
}
}
Asymmetric Signing (RSA / RS256)
In distributed microservices, authentication servers issue tokens using a private key, and downstream services verify them using the corresponding public key:
import com.auth0.jwt.JWT
import com.auth0.jwt.algorithms.Algorithm
import java.security.interfaces.RSAPrivateKey
import java.security.interfaces.RSAPublicKey
import java.util.Date
// Sign on Auth Service using RSA Private Key
fun signRsaToken(privateKey: RSAPrivateKey, userId: String): String {
val algorithm = Algorithm.RSA256(null, privateKey)
return JWT.create()
.withSubject(userId)
.withExpiresAt(Date(System.currentTimeMillis() + 3600_000))
.sign(algorithm)
}
// Verify on Resource Service using RSA Public Key
fun verifyRsaToken(publicKey: RSAPublicKey, token: String): String? {
val algorithm = Algorithm.RSA256(publicKey, null)
val verifier = JWT.require(algorithm).build()
return try {
verifier.verify(token).subject
} catch (e: Exception) {
null
}
}
Ktor Integration
In a Ktor backend, install the jwt authentication provider to protect endpoints automatically:
import com.auth0.jwt.JWT
import com.auth0.jwt.algorithms.Algorithm
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.auth.jwt.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
fun Application.configureSecurity() {
val secret = "super-secret-key"
val issuer = "https://auth.example.com"
val audience = "https://api.example.com"
install(Authentication) {
jwt("auth-jwt") {
realm = "Access to protected routes"
verifier(
JWT.require(Algorithm.HMAC256(secret))
.withAudience(audience)
.withIssuer(issuer)
.build()
)
validate { credential ->
if (credential.payload.audience.contains(audience)) {
JWTPrincipal(credential.payload)
} else {
null
}
}
}
}
routing {
authenticate("auth-jwt") {
get("/api/me") {
val principal = call.principal<JWTPrincipal>()!!
val userId = principal.payload.subject
val email = principal.payload.getClaim("email").asString()
call.respondText("Logged in as $userId ($email)")
}
}
}
}
Best Practices
- Never store sensitive secrets in claims: JWT payloads are Base64URL-encoded, not encrypted. Anyone can decode and inspect the payload.
- Enforce short lifetimes: Set short access token expiration times (e.g., 15–30 minutes) and use refresh tokens for prolonged sessions.
- Always validate
exp,iss, andaud: Ensure the token was intended for your specific service and has not expired. - Store secrets securely: Never commit secret keys or private keys into source control; inject them via environment variables or secret managers.