I'm focused on grasping the user's need: a Ktor server boilerplate in Kotlin, fortified with JWT authentication. I'm starting to zero in on the core components and envisioning the necessary architecture for the project. The aim is to make it as simple and secure as possible.
Outlining the Blueprint
\n\n
I've begun solidifying the project's foundation, zeroing in on the required dependencies and their specific versions. I'm focusing on the build.gradle.kts file and mapping out the necessary components to streamline the authentication process. I'm prioritizing clarity in the file's structure.
Structuring the Code
\n\n
My focus is now on mapping out the core code blocks within Application.kt. I'm breaking down the essential plugins: authentication, content negotiation, and the routing logic. Currently, I'm concentrating on the JWT configuration, ensuring it's robust and correctly integrated, and planning the routing structure for login and protected routes. The implementation order is being refined.
Crafting the Implementation
\n\n
Now, I'm immersed in creating modular code blocks. I'm starting with build.gradle.kts and then, crucially, the Security.kt plugin. I'm focusing on the JWT configuration: reading secrets, defining the verifier, and setting up the validator. The structure is being built around a secure and straightforward authentication flow, keeping maintainability at the forefront.
Planning the Implementation
\n\n
I'm now mapping out the detailed steps required to construct the Ktor server. I'm focusing on the Security.kt plugin, and how to handle user authentication and token generation. The key aspect is how to use the authentication plugin, JWT verifier and validator, to ensure secure access to protected routes. I'm also planning the login and protected routes.
Implementing the Structure
\n\n
My current focus is on organizing the overall project structure. I'm separating code into plugins for Security, Serialization, and Routing. I'm also preparing to create mock user authentication to simplify the example. The code is being broken down into logical sections to ensure maintainability and clarity.
Here is a clean, modular boilerplate for a Ktor 2.x server using Kotlin with JWT Authentication.
It follows the standard Ktor project structure, separating plugins (routing, security, serialization) for cleaner code.
Add the necessary Ktor artifacts, specifically ktor-server-auth-jwt.
kotlin
val ktor_version: String by project
val logback_version: String by project
plugins {
kotlin("jvm") version "1.9.22" // Or your specific version
id("io.ktor.plugin") version "2.3.7"
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:$ktor_version")
implementation("io.ktor:ktor-server-auth-jvm:$ktor_version")
implementation("io.ktor:ktor-server-auth-jwt-jvm:$ktor_version") // Key dependency
implementation("io.ktor:ktor-server-content-negotiation-jvm:$ktor_version")
implementation("io.ktor:ktor-serialization-kotlinx-json-jvm:$ktor_version")
implementation("io.ktor:ktor-server-netty-jvm:$ktor_version")
implementation("ch.qos.logback:logback-classic:$logback_version")
testImplementation("io.ktor:ktor-server-tests-jvm:$ktor_version")
testImplementation("org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version")
}
(Note: Ensure you have ktor_version=2.3.7 and logback_version=1.4.14 defined in your gradle.properties)
3. Data Models (src/main/kotlin/com/example/models/User.kt)
Simple DTOs for login requests.
kotlin
package com.example.models
import kotlinx.serialization.Serializable
@Serializable
data class User(val username: String, val password: String)
@Serializable
data class TokenResponse(val token: String)
Handles the login (generating the token) and protected routes.
kotlin
package com.example.plugins
import com.auth0.jwt.JWT
import com.auth0.jwt.algorithms.Algorithm
import com.example.models.TokenResponse
import com.example.models.User
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 generating tokens
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 {
// 1. Public Route: Login
post("/login") {
val user = call.receive<User>()
// TODO: Check database for username/password
if (user.username == "test" && user.password == "password") {
// Create the 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")
}
}
// 2. Protected Route
authenticate("auth-jwt") {
get("/hello") {
val principal = call.principal<JWTPrincipal>()
val username = principal!!.payload.getClaim("username").asString()
val expiresAt = principal.expiresAt?.time?.minus(System.currentTimeMillis())
call.respondText("Hello, $username! Token expires in $expiresAt ms")
}
}
}
}
7. Application Entry Point (src/main/kotlin/com/example/Application.kt)
Connects all the plugins together.
kotlin
package com.example
import com.example.plugins.*
import io.ktor.server.application.*
fun main(args: Array<String>) {
io.ktor.server.netty.EngineMain.main(args)
}
fun Application.module() {
configureSerialization()
configureSecurity() // Must be loaded before Routing if routes use Auth
configureRouting()
}
How to Test
Run the server (usually via Gradle run task or the Play button in IntelliJ).