-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Null Safety
-
Section 4: Object-Oriented Kotlin
-
Section 5: Functional Kotlin
-
Section 6: Coroutines
-
Section 7: Collections Deep Dive
-
Section 8: Type System Deep Dive
-
Section 9: Interop and Tooling
-
Section 10: Kotlin DSLs and Patterns
-
Section 11: Testing and Quality
-
Section 12: Server-Side Kotlin
-
Section 13: Practical Projects
-
Section 14: Interview Practice
-
Section 15: More Practice Exercises
-
Section 16: More Standard Library
-
Section 17: Multiplatform Kotlin
-
Section 18: kotlin.collections In Depth
-
Section 19: kotlin.text In Depth
-
Section 20: kotlin.ranges and kotlin.sequences
-
Section 21: kotlin.io and File Handling
-
Section 22: kotlinx.coroutines Deep Dive
-
Section 23: kotlin.reflect
-
Section 24: Android Development with Kotlin Overview
-
Section 25: Kotlin Multiplatform Deep Dive
-
Section 26: Kotlin for Backend Deep Dive
-
Section 27: Kotlin Design Patterns
-
Section 28: Advanced Language Features
-
Section 29: More Practice Exercises
-
Section 30: More Interview Practice
-
Section 31: Kotlin Type System Deep Dive
-
Section 32: Kotlin Null Safety Advanced
-
Section 33: Kotlin Testing Deep Dive
-
Section 34: Kotlin Build Tooling Deep Dive
-
Section 35: Kotlin Serialization
-
Section 36: Kotlin Performance Considerations
-
Section 37: Kotlin Native Overview
-
Section 38: Kotlin for Data and Scripting
-
Section 39: More Coroutines Practice
-
Section 40: More Android-Adjacent Patterns
-
Section 41: More Practical Projects
-
Section 42: More Design and Architecture Practice
-
Section 43: Kotlin Language Evolution
-
Section 44: More Interview and Review
-
Section 45: Kotlin Delegation Patterns Deep Dive
-
Section 46: Kotlin Annotations Deep Dive
-
Section 47: Kotlin for Gradle Plugin Development
-
Section 48: Kotlin Concurrency Beyond Coroutines
-
Section 49: Kotlin Compiler Internals
-
Section 50: Real-World Kotlin Case Studies
-
Section 51: Final Practice Projects
-
Section 52: Kotlin for Server-Side Reactive Programming
-
Section 53: More Practice and Drills
-
Section 54: Kotlin Security Practices
193: Building a REST API with Authentication in Ktor
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
GETroute at/profile. - Ensure the route is protected by the
"auth-jwt"authentication provider. - Extract the
userIdandemailclaims from theJWTPrincipal. - Respond with a string in the format:
"User ID: [id], Email: [email]". - Ensure that the
/healthendpoint (from the lesson) remains accessible to everyone without a token.
There are no comments for now.