Skip to Content
Course content

193: Building a REST API with Authentication in Ktor

Click on the "Edit" button in the top corner of the screen to edit your slide content.

By now, you're comfortable with Ktor's routing and basic request handling. But in the real world, you can't just leave your endpoints wide open for anyone to hit. Today, we're going to build a "Secret Note Store"—a simple API where users can save private notes, but only if they provide a valid JSON Web Token (JWT). I prefer JWTs for REST APIs because they're stateless; the server doesn't need to keep a session database, it just needs to verify the signature of the token.

Setting up the JWT Secret Sauce

First, we need to tell Ktor how to validate the tokens coming in. We'll use the Authentication plugin. I usually keep my secrets in environment variables, but for this example, I'll define them as constants. You'll need the ktor-server-auth-jwt dependency in your build.gradle.kts to make this work.

val jwtSecret = "my-super-secret-key-123"
val jwtIssuer = "https://auth.mynotes.com"
val jwtAudience = "notes-api"

install(Authentication) {
    jwt("auth-jwt") {
        realm = "Access to secret notes"
        verifier(
            JWT.require(Algorithm.HMAC256(jwtSecret))
                .withAudience(jwtAudience)
                .withIssuer(jwtIssuer)
                .build()
        )
        validate { credential ->
            if (credential.payload.audience.contains(jwtAudience)) {
                JWTPrincipal(credential.payload)
            } else {
                null
            }
        }
    }
}

Notice the validate block. That's where the actual logic happens. If it returns null, Ktor rejects the request. If it returns a JWTPrincipal, the request is allowed to proceed, and we can actually access the user's claims later in the route.

Defining the Secret Note Endpoint

Let's create a simple data model and a route to handle the note submission. I'm keeping it lean: just a POST request that takes a note string.

data class Note(val content: String, val userId: String)
val notesDatabase = mutableListOf<Note>()

routing {
    post("/notes") {
        val noteContent = call.receive<String>()
        val principal = call.principal<JWTPrincipal>()
        val userId = principal?.payload?.getClaim("userId")?.asString() ?: "unknown"
        
        notesDatabase.add(Note(noteContent, userId))
        call.respondText("Note saved for user $userId!")
    }
}

The "Why is this still open?" Moment

I'll admit, I've done this more times than I'd like to admit. I ran the server, sent a request using Postman without any Authorization header, and... it worked. I was confused for a second. I had installed the Authentication plugin, so why was the /notes endpoint still public?

The mistake was simple: installing the plugin defines how authentication works, but it doesn't automatically apply it to every route. In Ktor, authentication is explicit. I had created the "lock," but I forgot to actually put it on the door.

Locking down the Route

To fix this, you need to wrap your protected routes in an authenticate block. This block tells Ktor: "Only let requests through here if they satisfy the requirements of the specified authentication provider." In our case, that provider is "auth-jwt".

routing {
    authenticate("auth-jwt") {
        post("/notes") {
            val noteContent = call.receive<String>()
            val principal = call.principal<JWTPrincipal>()
            val userId = principal?.payload?.getClaim("userId")?.asString() ?: "unknown"
            
            notesDatabase.add(Note(noteContent, userId))
            call.respondText("Note saved for user $userId!")
        }
    }
    
    // This route remains public
    get("/health") {
        call.respondText("API is running!")
    }
}

Now, if you try to hit /notes without a Authorization: Bearer <token> header, Ktor will automatically return a 401 Unauthorized. It's clean, explicit, and keeps your business logic separate from your security logic.




📋 Practical Task

Implement a Protected User Profile Endpoint

You have been tasked with adding a new feature to the Secret Note Store. The API needs a GET /profile endpoint that returns the user's ID and their email address. Both of these pieces of information are stored as claims within the JWT token.

Your Task:

  • Create a GET route at /profile.
  • Ensure the route is protected by the "auth-jwt" authentication provider.
  • Extract the userId and email claims from the JWTPrincipal.
  • Respond with a string in the format: "User ID: [id], Email: [email]".
  • Ensure that the /health endpoint (from the lesson) remains accessible to everyone without a token.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.