Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 38 ยท Projects and Practice

Project: A Task API with Authentication and a Database

Build a complete REST API in Ktor: register and log in with JWT, own tasks per user, validate input, handle errors, store data with Exposed, paginate and test. Includes runnable core logic.

This project brings the whole course together in one realistic service: a task manager API where users register, log in, and manage their own tasks. It uses JWT authentication, Exposed for storage, validation and StatusPages for errors, and tests at the end. The important design lesson is authorization: logging in proves who you are, but every query must also make sure the data belongs to you.

About the examples. Real Ktor and Exposed code is shown read-only (the site has no Gradle or Ktor jars). The core rules (password hashing, token issue and check, ownership, pagination) are plain Kotlin you can run here. The token in the stand-in is a simplified HMAC-signed token to show the idea; in the real app use the Ktor JWT plugin and a vetted library.

1. The API

Endpoint Auth Purpose
POST /auth/register none Create an account (201, or 409 if the email exists)
POST /auth/login none Returns a token (200, 401 on wrong credentials)
GET /tasks?page=1&size=20&done=false token List my tasks, paginated
POST /tasks token Create a task (201, 400 if invalid)
GET /tasks/{id} token One of my tasks (404 if missing or not mine)
PATCH /tasks/{id} token Update title or done flag
DELETE /tasks/{id} token Delete (204)

Returning 404 instead of 403 for another user's task is deliberate: it does not reveal that the id exists.

2. Project structure

TEXT
src/main/kotlin/com/example/
  Application.kt        # main, module(): installs plugins, calls configure functions
  config/Settings.kt    # typed settings (see Configuration and Environments)
  db/Tables.kt          # Exposed tables, DatabaseFactory (pool + migrations)
  auth/Security.kt      # password hashing, JWT creation, authentication config
  tasks/TaskRoutes.kt   # routes
  tasks/TaskRepository.kt
  tasks/TaskModels.kt   # @Serializable request/response classes
src/test/kotlin/...     # testApplication tests

Routes talk to repositories; repositories talk to the database. Neither route code nor tests should know SQL details.

3. Registering and logging in: the rules

  • Hash passwords with a slow, salted algorithm (bcrypt, scrypt or Argon2). Never store or log the plain text. Compare in constant time.
  • Same error for wrong email and wrong password. "Invalid credentials" in both cases, so attackers cannot discover which emails exist (there is still a timing side channel; real systems also rate-limit login).
  • Normalize emails (trim, lowercase) before storing and comparing, and enforce a unique index.
  • Short-lived tokens. A token that expires in an hour limits what a stolen token can do.

The runnable core below implements those rules. The password hash is a deliberately simple salted SHA-256 so the example runs without libraries; do not use plain SHA-256 for real passwords.

Kotlin Core: registration, login and signed tokens (simplified)

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.

In the real app, the Authentication plugin does the verifying step for you:

Kotlin
install(Authentication) {
    jwt("auth-jwt") {
        realm = "tasks"
        verifier(JWT.require(Algorithm.HMAC256(settings.jwt.secret)).withIssuer(settings.jwt.issuer).build())
        validate { cred ->
            val id = cred.payload.getClaim("uid").asInt()
            if (id != null) UserPrincipal(id) else null
        }
        challenge { _, _ -> call.respond(HttpStatusCode.Unauthorized, ApiError("invalid or expired token")) }
    }
}

4. Ownership: the rule that prevents the worst bug

Authentication answers "who are you?". Authorization answers "may you do this?". For a multi-user API the most common serious vulnerability is broken object-level authorization: the client sends GET /tasks/42, the server loads task 42 and returns it without checking whose it is. The fix is simple and mechanical: every repository method takes the user id and filters by it. There should be no findById(id) without an owner.

Kotlin Core: owner-scoped repository with pagination

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.

5. Routes with the authenticated user

In the real app, authenticated routes live inside authenticate("auth-jwt") { ... }, and handlers read the principal:

Kotlin
fun Route.taskRoutes(repo: TaskRepository) {
    authenticate("auth-jwt") {
        route("/tasks") {
            get {
                val me = call.principal<UserPrincipal>()!!.id
                val page = call.request.queryParameters["page"]?.toIntOrNull() ?: 1
                val size = call.request.queryParameters["size"]?.toIntOrNull() ?: 20
                val done = call.request.queryParameters["done"]?.toBooleanStrictOrNull()
                call.respond(repo.list(me, page, size, done))
            }
            post {
                val me = call.principal<UserPrincipal>()!!.id
                val body = call.receive<NewTask>()            // validated by RequestValidation
                call.respond(HttpStatusCode.Created, repo.create(me, body.title))
            }
            get("/{id}") {
                val me = call.principal<UserPrincipal>()!!.id
                val id = call.parameters["id"]?.toIntOrNull() ?: throw BadRequestException("id must be a number")
                call.respond(repo.find(me, id) ?: throw NotFoundException())
            }
            delete("/{id}") {
                val me = call.principal<UserPrincipal>()!!.id
                val id = call.parameters["id"]?.toIntOrNull() ?: throw BadRequestException("id must be a number")
                call.respond(if (repo.delete(me, id)) HttpStatusCode.NoContent else HttpStatusCode.NotFound)
            }
        }
    }
}

StatusPages turns BadRequestException, NotFoundException and validation failures into a consistent JSON error body, so clients always see the same error shape (see Status Pages and Error Handling).

6. The Exposed repository

Kotlin
object Tasks : IntIdTable("tasks") {
    val ownerId = integer("owner_id").index()
    val title = varchar("title", 100)
    val done = bool("done").default(false)
    val createdAt = timestamp("created_at").defaultExpression(CurrentTimestamp)
}

class ExposedTaskRepository : TaskRepository {
    override suspend fun find(owner: Int, id: Int) = dbQuery {
        Tasks.selectAll().where { (Tasks.id eq id) and (Tasks.ownerId eq owner) }.singleOrNull()?.toTask()
    }

    override suspend fun list(owner: Int, page: Int, size: Int, done: Boolean?) = dbQuery {
        val query = Tasks.selectAll().where {
            (Tasks.ownerId eq owner) and (done?.let { Tasks.done eq it } ?: Op.TRUE)
        }
        val total = query.count().toInt()
        val items = query.orderBy(Tasks.id).limit(size).offset(((page - 1) * size).toLong()).map { it.toTask() }
        Page(items, page, size, total)
    }
}

The owner_id index matters: every query filters by it. Use migrations (see Connection Pooling and Migrations) rather than SchemaUtils.create in production, and add a foreign key to a users table. Beware of OFFSET pagination on huge tables; keyset pagination (WHERE id > :lastId ORDER BY id LIMIT :size) stays fast on deep pages.

7. Tests that prove the security rules

The most valuable tests for this API check what must not work:

Kotlin
@Test
fun userCannotReadAnothersTask() = testApplication {
    application { module(testSettings(), InMemoryTaskRepository()) }
    val client = jsonClient()
    val annToken = client.registerAndLogin("[email protected]")
    val bobToken = client.registerAndLogin("[email protected]")

    val created = client.post("/tasks") { bearerAuth(annToken); setJson(NewTask("private")) }.body<Task>()

    assertEquals(HttpStatusCode.NotFound, client.get("/tasks/${created.id}") { bearerAuth(bobToken) }.status)
    assertEquals(HttpStatusCode.Unauthorized, client.get("/tasks/${created.id}").status)
    assertEquals(HttpStatusCode.OK, client.get("/tasks/${created.id}") { bearerAuth(annToken) }.status)
}

Add tests for: expired and tampered tokens, duplicate registration (409), blank titles (400), page size clamping, and deletion of someone else's task (404, and the task still exists). See Testing with Fakes and Databases.

Ideas to extend it

  • Refresh tokens and logout (token revocation list).
  • Task labels with a many-to-many table (Exposed relations).
  • Rate limiting on /auth/login (Production Readiness).
  • A Dockerfile and Compose file with Postgres (Docker and Packaging).
  • Server-sent events that push task changes to the user's other devices (SSE).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why return 404 rather than 403 when a user requests someone else's task?

    A 404 hides existence, so users cannot probe for other people's ids.
  2. 2. What is broken object-level authorization?

    Authentication is not enough; every object access must also verify ownership.
  3. 3. How should login respond when the email exists but the password is wrong?

    Identical answers avoid leaking which emails are registered.
  4. 4. Why clamp the page size on the server?

    Never trust client-supplied limits; cap them.

Summary

  • Register, hash passwords with a real algorithm, give uniform login errors, and issue short-lived tokens.
  • Verify tokens with the Authentication plugin; keep secrets in configuration.
  • Scope every repository method by owner to prevent broken object-level authorization.
  • Validate input, clamp pagination and keep error responses consistent with StatusPages.
  • Test the negative cases: other users, missing tokens, expired tokens, bad input.

Next: Practice: Ktor Exercises