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
Authorizationheader to a specific resource in a server application.A server responds to a client with a
401(Unauthorized) response status and uses aWWW-Authenticateresponse header to provide information that the basic authentication scheme is used to protect a route. 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 without waiting the
WWW-Authenticateheader using thesendWithoutRequestfunction.Usually, a client displays a login dialog where a user can enter credentials. Then, a client makes a request with the
Authorizationheader 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
installblock.Provide the required credentials using BasicAuthCredentials and pass this object to the credentials function.
Configure the realm using the
realmproperty.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-Authenticateheader. You need to call thesendWithoutRequestfunction returning boolean and check the request parameters.install(Auth) { basic { // ... sendWithoutRequest { request -> request.url.host == "0.0.0.0" } } }