Skills DirectorySkills Directory
SkillsLearnSecurityCategoriesDocsCommunityBlog
Sign InSubmit Skill
Skills Directory

Security-tested agent skills for Claude, coding agents, and AI workflows.

Directory

  • Browse Skills
  • All Skills A–Z
  • Claude Skills
  • Claude Code Skills
  • Agent Skills
  • Categories
  • Submit a Skill

Learn

  • Learn Hub
  • Install Claude Skills
  • Write SKILL.md
  • Skills vs MCP
  • Directories Compared

Security

  • Security
  • Methodology
  • Secure Claude Skills
  • Security Badges

Company

  • About
  • Community
  • Blog
  • API Docs
  • Advertise

2026 Skills Directory. All rights reserved.

Back to skills

Kotlin Ktor

ASecurity

Use when building Ktor 3.x HTTP servers. Covers the non-obvious defaults and gotchas — CORS's method allowlist, StatusPages nearest-class exception matching, JWT validate-returning-null semantics, WebSocket protocol details — plus JWT/StatusPages/CORS/WebSocket install-block shapes.

2 stars
0 votes
0 copies
0 views
Added 9/19/2026
ai-agentsgokotlin

Works with

cli

Security Analysis

A100/100

Scanned 9/19/2026

Install to Claude Code

$npx -y skills add Mixard/fable-pack --skill kotlin-ktor --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Kotlin Ktor?

Add the live security badge to your README — it updates automatically with every re-scan.

Security grade badge for Kotlin Ktor
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/mixard-kotlin-ktor/badge)](https://www.skillsdirectory.com/skills/mixard-kotlin-ktor)

More formats (shields.io, HTML) on the badges page.

Download Zip
Files
SKILL.md
---
name: kotlin-ktor
description: Use when building Ktor 3.x HTTP servers. Covers the non-obvious defaults and gotchas — CORS's method allowlist, StatusPages nearest-class exception matching, JWT validate-returning-null semantics, WebSocket protocol details — plus JWT/StatusPages/CORS/WebSocket install-block shapes.
---

# Ktor 3.x Server Patterns

Ktor apps are configured as `Application` extension functions installing plugins, with routes as `Route` extension functions. Keep routes thin; push logic to services injected via Koin (`val userService by inject<UserService>()` at the top of the `Route.` extension function, not inside handlers).

```kotlin
fun Application.module() {
    configureSerialization()
    configureAuthentication()
    configureStatusPages()
    configureCORS()
    configureDI()
    configureRouting()
}
```

Protect a route subtree with `authenticate("jwt") { ... }` nested inside `route`.

## JWT authentication

```kotlin
fun Application.configureAuthentication() {
    val jwtSecret = environment.config.property("jwt.secret").getString()
    install(Authentication) {
        jwt("jwt") {
            realm = environment.config.property("jwt.realm").getString()
            verifier(
                JWT.require(Algorithm.HMAC256(jwtSecret))
                    .withAudience(environment.config.property("jwt.audience").getString())
                    .withIssuer(environment.config.property("jwt.issuer").getString())
                    .build()
            )
            validate { credential ->
                if (credential.payload.audience.contains(jwtAudience)) {
                    JWTPrincipal(credential.payload)
                } else null
            }
            challenge { _, _ ->
                call.respond(HttpStatusCode.Unauthorized, "Invalid or expired token")
            }
        }
    }
}
```

`validate` returning `null` rejects the request even when the token's signature verified correctly — this is where audience/claim checks belong, and forgetting an `else null` branch silently accepts any signed token regardless of claims.

All `environment.config.property(...)` values come back as strings — convert numbers with `.toInt()` even for things that look numeric in the YAML.

## StatusPages

Handlers are matched from specific exception types down to `Throwable` as a catch-all; `status(...)` handles response codes with no matching route (not exceptions):

```kotlin
fun Application.configureStatusPages() {
    install(StatusPages) {
        exception<ContentTransformationException> { call, cause ->
            call.respond(HttpStatusCode.BadRequest, "Invalid request body: ${cause.message}")
        }
        exception<IllegalArgumentException> { call, cause ->
            call.respond(HttpStatusCode.BadRequest, cause.message ?: "Bad request")
        }
        exception<Throwable> { call, cause ->
            call.application.log.error("Unhandled exception", cause)
            call.respond(HttpStatusCode.InternalServerError, "Internal server error")
        }
        status(HttpStatusCode.NotFound) { call, status ->
            call.respond(status, "Route not found")
        }
    }
}
```

`ContentTransformationException` is what `call.receive<T>()` throws on malformed bodies — register it alongside `IllegalArgumentException` and a `Throwable` catch-all. StatusPages picks the handler whose registered class is nearest to the thrown exception in its class hierarchy (`selectNearestParentClass`, unchanged from Ktor 1.x through 3.5); registration order in `install` is irrelevant, so `exception<Throwable>` is a safe catch-all wherever it sits. `require(...)` in a handler surfaces as 400 for free via the `IllegalArgumentException` handler.

## CORS

```kotlin
fun Application.configureCORS() {
    install(CORS) {
        allowHost("example.com", schemes = listOf("https"))
        allowHeader(HttpHeaders.ContentType)
        allowHeader(HttpHeaders.Authorization)
        allowMethod(HttpMethod.Put)
        allowMethod(HttpMethod.Delete)
        allowMethod(HttpMethod.Patch)
        allowCredentials = true
    }
}
```

GET/POST/HEAD are allowed by default; PUT/DELETE/PATCH require an explicit `allowMethod` or the browser preflight fails. `Authorization` likewise needs an explicit `allowHeader` — omitting it breaks JWT-bearing clients with no server-side error, only a browser-blocked CORS failure.

## WebSockets

```kotlin
fun Application.configureWebSockets() {
    install(WebSockets) {
        pingPeriod = 15.seconds
        timeout = 15.seconds
        maxFrameSize = 64 * 1024   // bump only if the protocol needs larger frames
        masking = false            // server-to-client frames are unmasked per RFC 6455
    }
}
```

`masking = false` is correct for the server side — RFC 6455 requires client-to-server frames to be masked but forbids masking on server-to-server frames; setting `masking = true` here produces frames some clients reject.

Iterating `connections` while broadcasting needs a snapshot under lock, or a `ConcurrentModificationException` hits when a client disconnects mid-broadcast:

```kotlin
val snapshot = synchronized(connections) { connections.toList() }
snapshot.forEach { it.session.send(message) }
```

## testApplication

The default `client` inside `testApplication` has no content negotiation installed — build one with `createClient { install(ContentNegotiation) { json() } }` to send/receive JSON bodies. For routes behind `authenticate("jwt")`, send a real signed test JWT (`bearerAuth(token)`); a fake/unsigned principal does not exercise the actual verifier path.

```kotlin
test("protected route requires JWT") {
    testApplication {
        application { /* configureAuthentication(), configureRouting(), etc. */ }
        val response = client.post("/users") { setBody(CreateUserRequest("Alice", "a@example.com")) }
        response.status shouldBe HttpStatusCode.Unauthorized
    }
}
```

Attribution

MixardMixard
View sourceMore from Mixard →
SSkills DirectorySkills Directory

Ship a skill? Prove it's safe.

Free 120-pattern security scan, letter grade, and an embeddable README badge.

Submit a skill

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

Comments (0)

No comments yet. Be the first to comment!

SSkills DirectorySkills Directory

Ship a skill? Prove it's safe.

Free 120-pattern security scan, letter grade, and an embeddable README badge.

Submit a skill

Related Skills

Caveman

Ultra-compressed communication mode. Cuts token usage ~75% by speaking like caveman while keeping full technical accuracy. Supports intensity levels: lite, full (default), ultra, wenyan-lite, wenyan-full, wenyan-ultra. Use when user says "caveman mode", "talk like caveman", "use caveman", "less tokens", "be brief", or invokes /caveman. Also auto-triggers when token efficiency is requested.

1023331 votes

Hyperplan

Adversarial multi-agent planning skill. Self-orchestrates 5 hostile category members (unspecified-low, unspecified-high, deep, ultrabrain, artistry) via team-mode for ruthless cross-critique debate, distills only the defensible insights, then MANDATORILY hands the distilled insight bundle to the `plan` agent for executable plan formalization. Use when planning needs maximum rigor and surfacing of weak assumptions, blind spots, and over-engineering. Triggers: 'hyperplan', 'hpp', '/hyperplan', ...

686011 votes

Mcp Code Execution

Routes multi-tool workflows through MCP servers for large datasets and pipelines. Use when Bash tool overhead is limiting throughput on data-heavy tasks.

3331 votes

catchup

Recovers prior coding-agent session context by running `catchup <agent> --since-compact`, which extracts a clean summary of a previous Codex, Claude Code, Antigravity, OpenCode, or Pi Agent session. Use when the user says "catch up", "what did the last session do", "get me up to speed", "I switched agents", or asks to recover/summarize a previous session before continuing. Do NOT use for the current conversation, git history, or any non-agent log.

611 votes

math-skill

A comprehensive mathematical reasoning skill for AI assistants — handles arithmetic to research-level problems with rigorous step-by-step reasoning, systematic verification, and transparent uncertainty handling

381 votes
View all in ai-agents →