Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 38 ยท Authentication

Bearer Tokens and JWT

Secure a Ktor API with JSON Web Tokens: how a JWT is built and signed, the jwt provider with verifier and validate, issuing tokens at login, expiry and common mistakes.

Browsers keep a session; APIs consumed by mobile apps, single-page apps and other services usually use tokens. The client logs in once, receives a token, and sends it as Authorization: Bearer <token> on every call. The server does not have to remember anything: the token itself proves who the client is. The most common token format is the JSON Web Token (JWT). This lesson shows how a JWT is built, how Ktor's jwt provider checks one, and how to issue tokens at login. The stand-in builds and verifies real HS256 JWTs with the JDK's crypto, so you can see every byte.

Anatomy of a JWT

A JWT is three Base64URL strings joined by dots:

TEXT
eyJhbGciOiJIUzI1NiJ9 . eyJzdWIiOiJhbm4iLCJyb2xlIjoiYWRtaW4ifQ . 9fE3...signature
      header                          payload (claims)                 signature
  • Header: the algorithm (HS256) and type.
  • Payload: claims, statements about the user and the token. Registered claims include sub (subject, the user), iss (issuer), aud (audience), exp (expiry time, seconds since 1970) and iat (issued at). You add custom ones such as role.
  • Signature: an HMAC (or RSA/ECDSA signature) over header.payload computed with a secret key. It proves nobody changed the header or claims.

Two crucial facts:

  1. The payload is encoded, not encrypted. Anyone holding the token can read it. Never put passwords or private data in it.
  2. Anyone can read a token, but only the holder of the key can create a valid one, so the server trusts the claims after verifying the signature.

Dependencies and configuration

Ktor uses the java-jwt library (auth0) for tokens:

Kotlin
dependencies {
    implementation("io.ktor:ktor-server-auth")
    implementation("io.ktor:ktor-server-auth-jwt")
}

Settings live in application.conf (see configuration):

TEXT
jwt {
    secret = "dev-only-secret-change-me"
    secret = ${?JWT_SECRET}
    issuer = "http://0.0.0.0:8080/"
    audience = "my-api-users"
    realm = "My API"
    expiresInSeconds = 3600
}

Verifying tokens: the jwt provider

Kotlin
import com.auth0.jwt.JWT
import com.auth0.jwt.algorithms.Algorithm
import io.ktor.server.auth.jwt.*

fun Application.module() {
    val secret = environment.config.property("jwt.secret").getString()
    val issuer = environment.config.property("jwt.issuer").getString()
    val audience = environment.config.property("jwt.audience").getString()
    val realm = environment.config.property("jwt.realm").getString()

    install(Authentication) {
        jwt("auth-jwt") {
            this.realm = realm
            verifier(
                JWT.require(Algorithm.HMAC256(secret))
                    .withAudience(audience)
                    .withIssuer(issuer)
                    .build()
            )
            validate { credential ->
                if (credential.payload.getClaim("username").asString().isNotEmpty())
                    JWTPrincipal(credential.payload)
                else null
            }
            challenge { _, _ ->
                call.respond(HttpStatusCode.Unauthorized, "Token is not valid or has expired")
            }
        }
    }

    routing {
        authenticate("auth-jwt") {
            get("/me") {
                val principal = call.principal<JWTPrincipal>()!!
                val username = principal.payload.getClaim("username").asString()
                val expiresAt = principal.expiresAt?.time
                call.respondText("Hello, $username. Token expires at $expiresAt")
            }
        }
    }
}

The verifier checks the signature, the issuer, the audience and (automatically) the exp claim. validate runs afterwards and lets you add your own rule (the claim you need exists, the user is not disabled) and build the principal. challenge customises the 401 body.

Issuing tokens at login

Protected routes need a way to get a token: a login route that verifies the password (as in Authentication Basics) and signs a JWT:

Kotlin
@Serializable data class LoginRequest(val username: String, val password: String)

post("/login") {
    val login = call.receive<LoginRequest>()
    val user = userService.verify(login.username, login.password)
        ?: return@post call.respond(HttpStatusCode.Unauthorized, "Invalid credentials")

    val token = JWT.create()
        .withAudience(audience)
        .withIssuer(issuer)
        .withClaim("username", user.name)
        .withClaim("role", user.role)
        .withExpiresAt(Date(System.currentTimeMillis() + 60 * 60 * 1000))
        .sign(Algorithm.HMAC256(secret))
    call.respond(hashMapOf("token" to token))
}

The client then sends Authorization: Bearer <token>.

Stand-in: build and verify a real HS256 JWT

This program implements the JWT mechanics with the JDK only: Base64URL, HMAC-SHA256, claim checks for issuer, audience and expiry, constant-time signature comparison, and rejection of tampered or "alg: none" tokens. The clock is injected, so the output is deterministic.

Kotlin Stand-in: signing and verifying a JWT

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Notice that editing the payload without the key fails the signature check, an expired token is rejected, and a token claiming alg: none is refused. Good libraries (including java-jwt as used by Ktor) pin the algorithm in the verifier, so the token cannot choose it.

Design advice

  • Short lifetimes: 15 minutes to an hour for access tokens. Because tokens cannot be revoked easily, use a refresh token (long-lived, stored server side, rotated on use) to obtain new access tokens.
  • Keep secrets out of code: the signing key comes from an environment variable or secret store. For multiple services, prefer asymmetric keys (RS256/ES256): the auth service signs with a private key and APIs verify with the public key (a JWKS endpoint).
  • Always send over HTTPS: a stolen token works for anyone until it expires.
  • Store tokens carefully on the client. In browsers, an HttpOnly cookie is safer against script theft than localStorage; the sessions lesson covers cookies.
  • Do not put sensitive data in claims. They are readable.
  • Use the bearer provider (bearer("name") { authenticate { token -> ... } }) instead of jwt when tokens are random strings you look up in a database or cache. That form allows instant revocation at the cost of a lookup.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the signature of a JWT protect?

    The signature provides integrity and authenticity, not secrecy.
  2. 2. Which data is safe to store in a JWT payload?

    Payloads are only Base64URL encoded, so keep them free of secrets.
  3. 3. A JWT's exp claim is in the past. What should the verifier do?

    Expired tokens are invalid; the client must log in again or use a refresh token.
  4. 4. Why does a verifier pin the algorithm (e.g. HMAC256) instead of trusting the token header?

    Trusting the header's algorithm lets attackers forge tokens, for example with alg none.

Summary

  • A JWT is header.payload.signature; claims are readable, the signature makes them tamper-evident.
  • In Ktor, jwt("name") { verifier(...); validate { ... }; challenge { ... } } plus authenticate("name") { } protects routes.
  • Issue tokens from a /login route after verifying a password; set an expiry.
  • Keep tokens short-lived, secrets out of code, and everything over HTTPS.

Next: Sessions and Cookies