Ktor 3.0.1 Help

Authentication and authorization

Ktor provides the Auth plugin to handle authentication and authorization in your client application. Typical usage scenarios include logging in users and gaining access to specific resources.

Supported authentication types

HTTP provides a general framework for access control and authentication. The Ktor client allows you to use the following HTTP authentication schemes:

  • Basic - uses Base64 encoding to provide a username and password. Generally is not recommended if not used in combination with HTTPS.

  • Digest - an authentication method that communicates user credentials in an encrypted form by applying a hash function to the username and password.

  • Bearer - an authentication scheme that involves security tokens called bearer tokens. For example, you can use this scheme as a part of OAuth flow to authorize users of your application by using external providers, such as Google, Facebook, Twitter, and so on.

Add dependencies

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

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

You can learn more about artifacts required by the Ktor client from Adding client dependencies.

Install Auth

To install the Auth plugin, pass it to the install function inside a client configuration block:

import io.ktor.client.* import io.ktor.client.engine.cio.* import io.ktor.client.plugins.auth.* //... val client = HttpClient(CIO) { install(Auth) { // Configure authentication } }

Now you can configure the required authentication provider.

Configure authentication

Step 1: Choose an authentication provider

To use a specific authentication provider (basic, digest, or bearer), you need to call the corresponding function inside the install block. For example, to use the basic authentication, call the basic function:

install(Auth) { basic { // Configure basic authentication } }

Inside the block, you can configure settings specific to this provider.

Step 2: (Optional) Configure the realm

Optionally, you can configure the realm using the realm property:

install(Auth) { basic { realm = "Access to the '/' path" // ... } }

You can create several providers with different realms to access different resources:

install(Auth) { basic { realm = "Access to the '/' path" // ... } basic { realm = "Access to the '/admin' path" // ... } }

In this case, the client chooses the necessary provider based on the WWW-Authenticate response header, which contains the realm.

Step 3: Configure a provider

To learn how to configure settings for a specific provider, see a corresponding topic:

Last modified: 02 April 2024