Ktor 1.5.4 Help

Basic and form

Add dependencies

To enable basic and form authentication, you need to include the ktor-auth artifact in the build script:

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

Usage

Ktor supports two methods of authentication with the user and raw password as credentials: basic and form.

  • basic

    install(Authentication) { basic("auth-basic") { realm = "Access to the '/' path" validate { credentials -> if (credentials.name == "jetbrains" && credentials.password == "foobar") { UserIdPrincipal(credentials.name) } else { null } }
  • form

    install(Authentication) { form("auth-form") { userParamName = "username" passwordParamName = "password" validate { credentials -> if(credentials.name == "jetbrains" && credentials.password == "foobar") { UserIdPrincipal(credentials.name) } else { null } } }

Both authentication providers have a method validate to provide a callback that must generate a Principal from given a UserPasswordCredential or null for invalid credentials. That callback is marked as suspending, so that you can validate credentials in an asynchronous fashion.

You can use several strategies for validating:

Manual credential validation

Since there is the validate callback for authentication, you can just put your code there. So you can do things like checking the password against a constant, authenticating using a database or composing several validation mechanisms.

install(Authentication) { basic("auth-basic") { realm = "Access to the '/' path" validate { credentials -> if (credentials.name == "jetbrains" && credentials.password == "foobar") { UserIdPrincipal(credentials.name) } else { null } }

Remember that both the name and the password from the credentials are arbitrary values. Remember to escape and/or validate them when accessing with those values to the file system, a database, when storing them, or generating HTML with its content, etc.

Validating using UserHashedTableAuth

There is a class that handles hashed passwords in-memory to authenticate UserPasswordCredential. You can populate it from constants in code or from another source. You can use predefined digest functions or your own.

Instantiating:

val digestFunction = getDigestFunction("SHA-256") { "ktor${it.length}" } val hashedUserTable = UserHashedTableAuth( table = mapOf( "jetbrains" to digestFunction("foobar"), "admin" to digestFunction("password") ), digester = digestFunction )

Configuring server/routes:

install(Authentication) { basic("auth-basic-hashed") { realm = "Access to the '/' path" validate { credentials -> hashedUserTable.authenticate(credentials) } } }
Last modified: 26 April 2021