Creating boilerplate code for Ktor
The user is requesting boilerplate code for a sample Ktor application that utilizes JWT authentication. I want to ensure it's concise yet complete, avoiding unnecessary verbosity. I should include essential files like build.gradle.kts, Application.kt, and necessary plugins such as Serialization, Security, and Routing.
It's important to provide a JWT configuration snippet, a user model, a login route that returns a token, and a protected route. Using Ktor 2.x with Kotlin, I'll aim for clarity with a few comments but without deep explanations. I’ll also clarify whether to use Gradle or Maven, leaning towards Gradle Kotlin DSL as directed by Ktor’s documentation. Lastly, I'll include the necessary JWT dependencies.Setting up Ktor boilerplate
I need to draft a Ktor main function that sets up an embedded server using Netty on port 8080. I'll also include a module() function to install necessary plugins. It’s crucial to keep the answer concise while providing the required code, as it might get bulky.
I’ll target Ktor version 2.3.x and Kotlin 1.9. The structure will consist of several files, primarily focusing on build.gradle.kts and the source code in src. I’ll create files for plugins like Serialization, Security, and Routing, but I might keep some functionality in Application.kt and AuthRoutes.kt for simplicity. I'll also consider following the plugin pattern recommended by Ktor documentation; that might enhance their boilerplate functionality.Configuring Ktor components
I need to establish key pieces for the Ktor application. In Serialization.kt, I’ll set up the configureSerialization function to install Content Negotiation with JSON.
For Security.kt, I will define JwtConfig with a secret and a function to create a token for the user. In configureSecurity(), I will set up JWT authentication to validate claims.
In Routing.kt, I’ll define routing functions, including a basic GET that responds with "OK," a login route under "/auth", and a protected endpoint.
I also need to include a LoginRequest data class, validate credentials for simplicity, and share instructions on how to run the server, along with required dependencies for serialization.Configuring Gradle file
For the Gradle configuration, I’ll set a specific version for Ktor; I'll use val ktor_version = "2.3.11" directly in the boilerplate for simplicity. Typically, this would be configured as an extra property, but keeping it simple works here.
In the build.gradle.kts, I want to specify plugins, using Kotlin version 1.9.23 since Ktor 2.3 supports it, rather than venturing into the newer Kotlin 2.0. I'll also include the application plugin. Additionally, I’ll set mainClass for the application plugin to "com.example.ApplicationKt" and start crafting the dependencies and tasks.Finalizing Ktor models and instructions
I’m wrapping up the Ktor setup with the LoginRequest and TokenResponse classes, both using kotlinx.serialization annotations. The LoginRequest holds the username and password, while TokenResponse includes the token details.
I need to mention the necessary imports for routing and security in my code. I’ve clarified the imports like io.ktor.server.request.* and ensured everything compiles properly.
Lastly, I’ll provide a sample curl command for logging in and retrieving the token, emphasizing that this is built for Ktor 2.x. This answer will be formatted as code, listing relevant files clearly while keeping any explanations brief. Below is a minimal but complete Ktor (2.x) server boilerplate with JWT authentication.
Gradle build file
build.gradle.kts
plugins {
kotlin("jvm") version "1.9.23"
application
}
application {
mainClass.set("com.example.ApplicationKt")
}
repositories {
mavenCentral()
}
val ktor_version = "2.3.11"
val logback_version = "1.5.6"
val java_jwt_version = "4.4.0"
dependencies {
implementation("io.ktor:ktor-server-core-jvm:$ktor_version")
implementation("io.ktor:ktor-server-netty-jvm:$ktor_version")
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-auth-jvm:$ktor_version")
implementation("io.ktor:ktor-server-auth-jwt-jvm:$ktor_version")
implementation("ch.qos.logback:logback-classic:$logback_version")
implementation("com.auth0:java-jwt:$java_jwt_version")
testImplementation(kotlin("test"))
testImplementation("io.ktor:ktor-server-tests-jvm:$ktor_version")
}
kotlin {
jvmToolchain(17)
}
Application entry point
src/main/kotlin/com/example/Application.kt
package com.example
import com.example.plugins.configureRouting
import com.example.plugins.configureSecurity
import com.example.plugins.configureSerialization
import io.ktor.server.application.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
fun main() {
embeddedServer(
Netty,
port = 8080,
host = "0.0.0.0"
) {
configureSerialization()
configureSecurity()
configureRouting()
}.start(wait = true)
}
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
ignoreUnknownKeys = true
isLenient = true
}
)
}
}
JWT configuration and security
src/main/kotlin/com/example/plugins/Security.kt
package com.example.plugins
import com.auth0.jwt.JWT
import com.auth0.jwt.JWTVerifier
import com.auth0.jwt.algorithms.Algorithm
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.auth.jwt.*
import io.ktor.server.response.*
import java.util.*
object JwtConfig {
// TODO: Load these from environment / config in real apps
private const val secret = "very_secret_jwt_key_change_me"
private const val issuer = "ktor-jwt-example"
private const val audience = "ktor-jwt-audience"
const val realm = "Access to 'protected' routes"
private val algorithm: Algorithm = Algorithm.HMAC256(secret)
val verifier: JWTVerifier = JWT
.require(algorithm)
.withIssuer(issuer)
.withAudience(audience)
.build()
fun generateToken(
subject: String,
expiresInSeconds: Long = 3600
): String {
val now = System.currentTimeMillis()
val expiresAt = Date(now + expiresInSeconds * 1000)
return JWT.create()
.withSubject(subject)
.withIssuer(issuer)
.withAudience(audience)
.withClaim("username", subject)
.withIssuedAt(Date(now))
.withExpiresAt(expiresAt)
.sign(algorithm)
}
}
fun Application.configureSecurity() {
install(Authentication) {
jwt("auth-jwt") {
realm = JwtConfig.realm
verifier(JwtConfig.verifier)
validate { credential ->
val username = credential.payload.getClaim("username").asString()
if (!username.isNullOrBlank()) {
JWTPrincipal(credential.payload)
} else {
null
}
}
challenge { _, _ ->
call.respond(
HttpStatusCode.Unauthorized,
"Token is not valid or has expired"
)
}
}
}
}
Models for requests/responses
src/main/kotlin/com/example/models/LoginRequest.kt
package com.example.models
import kotlinx.serialization.Serializable
@Serializable
data class LoginRequest(
val username: String,
val password: String
)
src/main/kotlin/com/example/models/TokenResponse.kt
package com.example.models
import kotlinx.serialization.Serializable
@Serializable
data class TokenResponse(
val token: String,
val tokenType: String,
val expiresIn: Long
)
Routing with public and protected endpoints
src/main/kotlin/com/example/plugins/Routing.kt
package com.example.plugins
import com.example.models.LoginRequest
import com.example.models.TokenResponse
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.*
fun Application.configureRouting() {
routing {
get("/") {
call.respondText("Ktor JWT boilerplate is running")
}
route("/auth") {
post("/login") {
val credentials = call.receive<LoginRequest>()
// TODO: Replace with real user lookup & password verification
if (credentials.username == "test" && credentials.password == "password") {
val expiresIn = 3600L
val token = JwtConfig.generateToken(credentials.username, expiresIn)
call.respond(
TokenResponse(
token = token,
tokenType = "Bearer",
expiresIn = expiresIn
)
)
} else {
call.respond(HttpStatusCode.Unauthorized, "Invalid username or password")
}
}
}
authenticate("auth-jwt") {
get("/protected") {
val principal = call.principal<JWTPrincipal>()
val username = principal?.getClaim("username", String::class)
call.respond(
mapOf(
"message" to "Hello, $username! This is a protected endpoint."
)
)
}
}
}
}
How to run and test
- Run the server:
./gradlew run
# or on Windows:
# gradlew.bat run
- Get a token (dummy user:
test / password):
curl -X POST http://localhost:8080/auth/login \
-H "Content-Type: application/json" \
-d '{"username":"test","password":"password"}'
You’ll receive JSON containing a token.
- Call the protected endpoint:
curl http://localhost:8080/protected \
-H "Authorization: Bearer <PASTE_TOKEN_HERE>"
You should see a JSON message confirming access.
If you want, I can extend this boilerplate with user persistence (e.g., in-memory repository or database + password hashing).