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:
A client makes a request to a protected resource in a server application without the
Authorizationheader.The server responds with a
401 Unauthorizedresponse status and uses aWWW-Authenticateresponse header to indicate that Basic authentication is required. A typicalWWW-Authenticateheader 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-Authenticateheader – by using thesendWithoutRequest()function.The client typically prompts the user for credentials. It then makes a request with the
Authorizationheader containing a username and password pair encoded using Base64, for example:Authorization: Basic amV0YnJhaW5zOmZvb2JhcgThe 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:
Call the
basicfunction inside theinstall(Auth)block.Provide the required credentials using
BasicAuthCredentialsand pass this object to thecredentialsfunction.Configure the realm using the
realmproperty.val client = HttpClient(CIO) { install(Auth) { basic { credentials { BasicAuthCredentials(username = "jetbrains", password = "foobar") } realm = "Access to the '/' path" } } }(Optional) Enable preemptive authentication using the
sendWithoutRequestfunction, 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" } } }(Optional) Disable credential caching. By default, credentials returned by the
credentials {}provider are cached for reuse across requests. You can disable caching with thecacheTokensoption: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.