Basic authentication
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 without the
Authorization
header to a specific resource in a server application.A server responds to a client with a
401
(Unauthorized) response status and uses aWWW-Authenticate
response header to provide information that the basic authentication scheme is used to protect a route. A typicalWWW-Authenticate
header looks like this:WWW-Authenticate: Basic realm="Access to the '/' path", charset="UTF-8"The Ktor client allows you to send credentials without waiting the
WWW-Authenticate
header using thesendWithoutRequest
function.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 amV0YnJhaW5zOmZvb2JhcgA server validates 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 as follows:
Call the basic function inside the
install
block.Provide the required credentials using BasicAuthCredentials and pass this object to the credentials function.
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" } } }Optionally, enable sending credentials in the initial request without waiting for a
401
(Unauthorized) response with theWWW-Authenticate
header. You need to call thesendWithoutRequest
function returning boolean and check the request parameters.install(Auth) { basic { // ... sendWithoutRequest { request -> request.url.host == "0.0.0.0" } } }