Ktor 3.4.0 Help

Basic authentication in Ktor Client

The Basic authentication scheme can be used for logging in users. In this scheme, user credentials are transmitted as username/password pairs encoded using Base64.

Basic authentication flow

The basic authentication flow looks as follows:

  1. A client makes a request to a protected resource in a server application without the Authorization header.

  2. The server responds with a 401 Unauthorized response status and uses a WWW-Authenticate response header to indicate that Basic authentication is required. A typical WWW-Authenticate header looks like this:

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

    The Ktor client allows you to send credentials preemptively – without waiting for the WWW-Authenticate header – by using the sendWithoutRequest() function.

  3. The client typically prompts the user for credentials. It then makes a request with the Authorization header containing a username and password pair encoded using Base64, for example:

    Authorization: Basic amV0YnJhaW5zOmZvb2Jhcg

  4. The server validates the credentials sent by the client and responds with the requested content.

Configure basic authentication

To send user credentials in the Authorization header using the Basic scheme, you need to configure the basic authentication provider:

  1. Call the basic function inside the install(Auth) block.

  2. Provide the required credentials using BasicAuthCredentials and pass this object to the credentials function.

  3. Configure the realm using the realm property.

    val client = HttpClient(CIO) { install(Auth) { basic { credentials { BasicAuthCredentials(username = "jetbrains", password = "foobar") } realm = "Access to the '/' path" } } }

  4. (Optional) Enable preemptive authentication using the sendWithoutRequest function, which checks the request parameters and decides whether to attach credentials to the initial request.

    install(Auth) { basic { // ... sendWithoutRequest { request -> request.url.host == "0.0.0.0" } } }
  5. (Optional) Disable credential caching. By default, credentials returned by the credentials {} provider are cached for reuse across requests. You can disable caching with the cacheTokens option:

    basic { cacheTokens = false // Reloads credentials for every request // ... }

    Disabling caching is useful when credentials may change during the client session or must reflect the latest stored state.

19 December 2025