// =============================================
// Ktor Server with JWT Authentication Boilerplate
// =============================================
//
// This is a minimal, self-contained boilerplate for a Kotlin Ktor server with JWT authentication.
// It includes:
// - Login endpoint (/login) to authenticate and issue JWT tokens.
// - Protected endpoint (/protected) accessible only with valid JWT.
// - Hardcoded users for simplicity (username: "user", password: "pass").
// - Token expires in 1 hour.
// - Uses Netty engine, JSON serialization.
//
// ## Setup Instructions
//
// 1. Create a new Gradle project with Kotlin JVM.
// 2. Add the following to `build.gradle.kts` (plugins and dependencies):
//
// ```kotlin
// plugins {
// kotlin("jvm") version "1.9.20"
// kotlin("plugin.serialization") version "1.9.20"
// application
// }
//
// dependencies {
// implementation("io.ktor:ktor-server-core:2.3.7")
// implementation("io.ktor:ktor-server-netty:2.3.7")
// implementation("io.ktor:ktor-server-content-negotiation:2.3.7")
// implementation("io.ktor:ktor-serialization-kotlinx-json:2.3.7")
// implementation("io.ktor:ktor-server-auth-jwt:2.3.7")
// implementation("io.ktor:ktor-server-auth:2.3.7")
// implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.6.0")
// implementation("com.auth0:java-jwt:4.4.0")
// implementation("ch.qos.logback:logback-classic:1.4.11")
// }
//
// application {
// mainClass.set("MainKt")
// }
// ```
//
// 3. Replace the content of `src/main/kotlin/Main.kt` (or `Application.kt`) with the code below.
// 4. Run `./gradlew run` or from IDE.
// 5. Test:
// - POST /login: `{"username":"user","password":"pass"}` → returns `{"token":"..."}`
// - GET /protected: Use `Authorization: Bearer <token>` header.
import com.auth0.jwt.JWT
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.engine.*
import io.ktor.server.netty.*
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.serialization.kotlinx.json.*
import kotlinx.serialization.Serializable
import java.util.*
// =============================================
// Configuration
// =============================================
object JWTConfig {
const val SECRET = "my-super-secret-key-change-in-production" // Change this!
const val ISSUER = "ktor-jwt-boilerplate"
const val AUDIENCE = "ktor-clients"
fun verifier(secret: String) = JWT
.require(Algorithm.HMAC256(secret))
.withIssuer(ISSUER)
.withAudience(AUDIENCE)
.build()
}
// =============================================
// Data Classes
// =============================================
@Serializable
data class LoginCredentials(val username: String, val password: String)
@Serializable
data class LoginResponse(val token: String)
@Serializable
data class UserInfo(val username: String, val id: Int)
// =============================================
// Utility Functions
// =============================================
fun generateToken(username: String, userId: Int, secret: String): String = JWT.create()
.withAudience(JWTConfig.AUDIENCE)
.withIssuer(JWTConfig.ISSUER)
.withSubject(username)
.withClaim("id", userId)
.withExpiresAt(Date(System.currentTimeMillis() + 60 * 60 * 1000)) // 1 hour
.sign(Algorithm.HMAC256(secret))
// =============================================
// Application Module
// =============================================
fun Application.module() {
install(ContentNegotiation) {
json()
}
val jwtVerifier = JWTConfig.verifier(JWTConfig.SECRET)
val secret = JWTConfig.SECRET
install(Authentication) {
jwt("auth-jwt") {
realm = "Ktor JWT Boilerplate"
verifier(jwtVerifier)
validate { credential ->
if (credential.payload.audience.contains(JWTConfig.AUDIENCE) &&
credential.payload.issuer == JWTConfig.ISSUER
) {
JWTPrincipal(credential.payload)
} else {
null
}
}
challenge { defaultScheme, realm ->
call.respond(HttpStatusCode.Unauthorized, "Token is not valid or has expired")
}
}
}
routing {
// Public login route
post("/login") {
val credentials = call.receive<LoginCredentials>()
// Hardcoded user validation (replace with DB/service in real app)
if (credentials.username == "user" && credentials.password == "pass") {
val token = generateToken(credentials.username, 1, secret)
call.respond(LoginResponse(token))
} else {
call.respond(HttpStatusCode.BadRequest, "Invalid credentials")
}
}
// Protected routes
authenticate("auth-jwt") {
get("/protected") {
val principal = call.principal<JWTPrincipal>()
val username = principal?.payload?.subject ?: "Unknown"
val userId = principal?.payload?.getClaim("id")?.asInt() ?: -1
call.respond(UserInfo(username, userId))
}
// Example: Another protected route
get("/admin") {
val principal = call.principal<JWTPrincipal>()
// Add role-based check if needed
if (principal?.payload?.getClaim("role")?.asString() == "admin") {
call.respondText("Admin access granted!")
} else {
call.respond(HttpStatusCode.Forbidden, "Admin role required")
}
}
}
// Health check (public)
get("/") {
call.respondText("Ktor JWT Boilerplate Server is running!")
}
}
}
// =============================================
// Main Entry Point
// =============================================
fun main() {
embeddedServer(
Netty,
port = 8080,
host = "0.0.0.0",
module = Application::module
).start(wait = true)
}
Additional Notes
Security: Hardcoded secret/user—change immediately for production. Use environment variables (e.g., System.getenv("JWT_SECRET")) and a secure key manager.
Extensions:
Add database (e.g., Exposed/Kotlinx-datetime) for users.