Ktor 3.0.0-rc-1 Help

HSTS

The HSTS plugin adds the required HTTP Strict Transport Security headers to the request according to the RFC 6797. When the browser receives HSTS policy headers, it no longer attempts to connect to the server with insecure connections for a given period.

Add dependencies

To use HSTS, you need to include the ktor-server-hsts artifact in the build script:

implementation("io.ktor:ktor-server-hsts:$ktor_version")
implementation "io.ktor:ktor-server-hsts:$ktor_version"
<dependency> <groupId>io.ktor</groupId> <artifactId>ktor-server-hsts-jvm</artifactId> <version>${ktor_version}</version> </dependency>

Install HSTS

To install the HSTS plugin to the application, pass it to the install function in the specified module. The code snippets below show how to install HSTS...

  • ... inside the embeddedServer function call.

  • ... inside the explicitly defined module, which is an extension function of the Application class.

import io.ktor.server.engine.* import io.ktor.server.netty.* import io.ktor.server.application.* import io.ktor.server.plugins.hsts.* fun main() { embeddedServer(Netty, port = 8080) { install(HSTS) // ... }.start(wait = true) }
import io.ktor.server.application.* import io.ktor.server.plugins.hsts.* // ... fun Application.module() { install(HSTS) // ... }

The HSTS plugin can also be installed to specific routes. This might be useful if you need different HSTS configurations for different application resources.

Configure HSTS

HSTS exposes its settings via HSTSConfig. The example below shows how to use the maxAgeInSeconds property to specify how long the client should keep the host in a list of known HSTS hosts:

install(HSTS) { maxAgeInSeconds = 10 }

You can also provide different HSTS configurations for different hosts using withHost:

install(HSTS) { maxAgeInSeconds = 10 withHost("sample-host") { maxAgeInSeconds = 60 includeSubDomains = false } }

You can find the full example here: ssl-engine-main-hsts.

Last modified: 02 April 2024