Refining the Core Concept
I've been drilling down on the fundamental needs. Essentially, this boilerplate must offer a streamlined starting point for building Ktor servers with robust JWT security. It needs to be easy to grasp and customize, addressing authentication and authorization needs. Current efforts are focused on distilling the essential components.
Mapping Dependencies & Structure
Now I'm focusing on the Ktor dependencies and app structure. I'm prioritizing kotlinx.serialization for JSON handling, believing it aligns well with Kotlin's strengths. The core build.gradle.kts is shaping up with essential server dependencies and JWT plugins. I'm outlining Application.kt, application.conf, and key plugins – ContentNegotiation, Authentication (JWT), and Routing, plus simplified domain logic: user data and token generation.
Implementing Logging and Config
I'm now integrating Logback for logging. Config is next, where I'll demonstrate using application.conf (or yaml) instead of hardcoding secrets - the goal being to highlight the necessary keys: secret, issuer, audience, and realm. My current focus is crafting the core modules: Application.kt, Security.kt, and Routing.kt. The initial setup is coming together.
Designing API Endpoints
I'm now zeroing in on the login endpoint. It's crucial that this route, secured with authenticate("auth-jwt"), handles extracting the user's principal data and responding appropriately. I'm finalizing data models for User login requests and UserResponse/TokenResponse. I'm also planning to refine my design and I am also reminding myself to use ENV vars for production secrets.
Structuring the Output
I'm now nailing down the structure of the final output, focusing on documentation. I'm outlining the key files: the build script with dependencies, configuration, the main application, plugins for serialization, security (with JWT logic), and routing (with endpoints). The last step is to add simple curl examples on testing the solution. Finally, I'll walk through a final code review to check for consistency and correctness.
Here is a complete, runnable boilerplate for a Ktor 2.x (and 3.x compatible) server using Kotlin, featuring JWT Authentication, Content Negotiation (JSON), and a structured project layout.
Prerequisites
- IntelliJ IDEA
- JDK 11+ (JDK 17/21 recommended)
Project Structure
src
└── main
├── kotlin
│ └── com.example
│ ├── Application.kt
│ ├── models
│ │ └── User.kt
│ └── plugins
│ ├── Routing.kt
│ ├── Security.kt
│ └── Serialization.kt
└── resources
├── application.conf
└── logback.xml
1. Dependencies (build.gradle.kts)
Add the specific Ktor dependencies for Netty, Auth JWT, and Serialization.
val ktor_version: String by project
val kotlin_version: String by project
val logback_version: String by project
plugins {
kotlin("jvm") version "1.9.22" // Or your current version
id("io.ktor.plugin") version "2.3.8" // Or 3.x
id("org.jetbrains.kotlin.plugin.serialization") version "1.9.22"
}
group = "com.example"
version = "0.0.1"
application {
mainClass.set("com.example.ApplicationKt")
val isDevelopment: Boolean = project.ext.has("development")
applicationDefaultJvmArgs = listOf("-Dio.ktor.development=$isDevelopment")
}
repositories {
mavenCentral()
}
dependencies {
implementation("io.ktor:ktor-server-core-jvm")
implementation("io.ktor:ktor-server-auth-jvm")
implementation("io.ktor:ktor-server-auth-jwt-jvm") // Crucial for JWT
implementation("io.ktor:ktor-server-netty-jvm")
implementation("io.ktor:ktor-server-content-negotiation-jvm")
implementation("io.ktor:ktor-serialization-kotlinx-json-jvm")
implementation("ch.qos.logback:logback-classic:$logback_version")
testImplementation("io.ktor:ktor-server-tests-jvm")
testImplementation("org.jetbrains.kotlin:kotlin-test-junit")
}
2. Configuration (src/main/resources/application.conf)
We define the server port and JWT configuration settings here.
Note: In a real environment, pass the secret via environment variables.
ktor {
deployment {
port = 8080
port = ${?PORT}
}
application {
modules = [ com.example.ApplicationKt.module ]
}
}
jwt {
domain = "https://jwt-provider-domain/"
audience = "jwt-audience"
realm = "ktor sample app"
secret = "secret" # Change this to a strong secret in production
}
3. Entry Point (src/main/kotlin/com/example/Application.kt)
This sets up the engine and loads the plugins.
package com.example
import com.example.plugins.*
import io.ktor.server.application.*
import io.ktor.server.netty.*
fun main(args: Array<String>) = EngineMain.main(args)
fun Application.module() {
configureSerialization()
configureSecurity() // JWT logic resides here
configureRouting()
}
4. Models (src/main/kotlin/com/example/models/User.kt)
Simple data classes for requests and responses.
package com.example.models
import kotlinx.serialization.Serializable
@Serializable
data class UserCredentials(val username: String, val password: String)
@Serializable
data class TokenResponse(val token: String)
@Serializable
data class ProtectedData(val username: String, val message: String)
5. Security Plugin (src/main/kotlin/com/example/plugins/Security.kt)
This is the core logic. It configures the JWT verifier and the validation logic.
package com.example.plugins
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.*
fun Application.configureSecurity() {
// 1. Read config from application.conf
val jwtAudience = environment.config.property("jwt.audience").getString()
val jwtDomain = environment.config.property("jwt.domain").getString()
val jwtRealm = environment.config.property("jwt.realm").getString()
val jwtSecret = environment.config.property("jwt.secret").getString()
authentication {
jwt("auth-jwt") {
realm = jwtRealm
verifier(
JWT
.require(Algorithm.HMAC256(jwtSecret))
.withAudience(jwtAudience)
.withIssuer(jwtDomain)
.build()
)
// 2. Validate the token payload
validate { credential ->
if (credential.payload.audience.contains(jwtAudience) &&
credential.payload.getClaim("username").asString() != "") {
JWTPrincipal(credential.payload)
} else {
null
}
}
// Optional: Handle authentication failures nicely
challenge { defaultScheme, realm ->
throw io.ktor.server.plugins.BadRequestException("Token is invalid or expired")
}
}
}
}
6. Serialization Plugin (src/main/kotlin/com/example/plugins/Serialization.kt)
package com.example.plugins
import io.ktor.serialization.kotlinx.json.*
import io.ktor.server.application.*
import io.ktor.server.plugins.contentnegotiation.*
import kotlinx.serialization.json.Json
fun Application.configureSerialization() {
install(ContentNegotiation) {
json(Json {
prettyPrint = true
isLenient = true
ignoreUnknownKeys = true
})
}
}
7. Routing Plugin (src/main/kotlin/com/example/plugins/Routing.kt)
This handles the Login (token generation) and Protected Routes.
package com.example.plugins
import com.auth0.jwt.JWT
import com.auth0.jwt.algorithms.Algorithm
import com.example.models.*
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.auth.jwt.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import java.util.*
fun Application.configureRouting() {
// Read config for token generation
val jwtAudience = environment.config.property("jwt.audience").getString()
val jwtDomain = environment.config.property("jwt.domain").getString()
val jwtSecret = environment.config.property("jwt.secret").getString()
routing {
// Public Route: Health Check
get("/") {
call.respondText("Server is running")
}
// Public Route: Login
post("/login") {
val user = call.receive<UserCredentials>()
// TODO: Check credentials against a real database here
if (user.username == "admin" && user.password == "password") {
// Generate Token
val token = JWT.create()
.withAudience(jwtAudience)
.withIssuer(jwtDomain)
.withClaim("username", user.username)
.withExpiresAt(Date(System.currentTimeMillis() + 60000)) // 1 minute
.sign(Algorithm.HMAC256(jwtSecret))
call.respond(TokenResponse(token))
} else {
call.respond(HttpStatusCode.Unauthorized, "Invalid credentials")
}
}
// Protected Routes
authenticate("auth-jwt") {
get("/api/me") {
// Extract data from the token
val principal = call.principal<JWTPrincipal>()
val username = principal!!.payload.getClaim("username").asString()
val expiresAt = principal.expiresAt?.time.toString()
call.respond(ProtectedData(username, "Token expires at: $expiresAt"))
}
}
}
}
How to Run and Test
-
Start the server: Run Application.kt in IntelliJ.
-
Request a Token (Login):
Use Postman or cURL.
curl -X POST http://localhost:8080/login \
-H "Content-Type: application/json" \
-d '{"username": "admin", "password": "password"}'
Response: {"token": "eyJ0eXAi..."}
-
Access Protected Route:
Copy the token from step 2.
curl -X GET http://localhost:8080/api/me \
-H "Authorization: Bearer <YOUR_TOKEN_HERE>"
Response: {"username": "admin", "message": "Token expires at: ..."}
-
Test Failure:
Make the same GET request without the Authorization header or with a fake token to see a 401 Unauthorized error.