Ktor 3.0.0-beta-1 Help

Basic authentication

The Basic authentication scheme is a part of the HTTP framework used for access control and authentication. In this scheme, user credentials are transmitted as username/password pairs encoded using Base64.

Ktor allows you to use basic authentication for logging in users and protecting specific routes. You can get general information about authentication in Ktor in the Authentication and authorization section.

Add dependencies

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

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

Basic authentication flow

The basic authentication flow looks as follows:

  1. A client makes a request without the Authorization header to a specific route in a server application.

  2. A server responds to a client with a 401 (Unauthorized) response status and uses a WWW-Authenticate response header to provide information that the basic authentication scheme is used to protect a route. A typical WWW-Authenticate header looks like this:

    WWW-Authenticate: Basic realm="Access to the '/' path", charset="UTF-8"

    In Ktor, you can specify the realm and charset using corresponding properties when configuring the basic authentication provider.

  3. Usually, a client displays a login dialog where a user can enter credentials. Then, a client makes a request with the Authorization header containing a username and password pair encoded using Base64, for example:

    Authorization: Basic amV0YnJhaW5zOmZvb2Jhcg
  4. A server validates credentials sent by a client and responds with the requested content.

Install basic authentication

To install the basic authentication provider, call the basic function inside the install block:

import io.ktor.server.application.* import io.ktor.server.auth.* // ... install(Authentication) { basic { // Configure basic authentication } }

You can optionally specify a provider name that can be used to authenticate a specified route.

Configure basic authentication

To get a general idea of how to configure different authentication providers in Ktor, see Configure Authentication. In this section, we'll see on configuration specifics of the basic authentication provider.

Step 1: Configure a basic provider

The basic authentication provider exposes its settings via the BasicAuthenticationProvider.Configuration class. In the example below, the following settings are specified:

  • The realm property sets the realm to be passed in the WWW-Authenticate header.

  • The validate function validates a username and password.

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

The validate function checks UserPasswordCredential and returns a UserIdPrincipal in the case of successful authentication or null if authentication fails.

Step 2: Protect specific resources

After configuring the basic provider, you can protect specific resources in our application using the authenticate function. In the case of successful authentication, you can retrieve an authenticated UserIdPrincipal inside a route handler using the call.principal function and get a name of an authenticated user.

routing { authenticate("auth-basic") { get("/") { call.respondText("Hello, ${call.principal<UserIdPrincipal>()?.name}!") } } }

Validate with UserHashedTableAuth

Ktor allows you to use UserHashedTableAuth to validate users stored in an in-memory table that keeps usernames and password hashes. This allows you not to compromise user passwords if your data source is leaked.

To use UserHashedTableAuth for validating users, follow the steps below:

  1. Create a digest function with the specified algorithm and salt provider using the getDigestFunction function:

    val digestFunction = getDigestFunction("SHA-256") { "ktor${it.length}" }
  2. Initialize a new instance of UserHashedTableAuth and specify the following properties:

    • Provide a table of usernames and hashed passwords using the table property.

    • Assign a digest function to the digester property.

    val hashedUserTable = UserHashedTableAuth( table = mapOf( "jetbrains" to digestFunction("foobar"), "admin" to digestFunction("password") ), digester = digestFunction )
  3. Inside the validate function, call the UserHashedTableAuth.authenticate function to authenticate a user and return an instance of UserIdPrincipal if the credentials are valid:

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