A simple way to set a token for requests using Ktor

Yauhen Slizh
2 min read2 hours ago

--

Ktor is a third-party library that helps simplify networking for KMM projects. Additionally, Ktor can also be used in pure Android projects. Ktor provides a plugin pattern to extend behavior during the execution of requests and responses. The idea is very similar to interceptors for OkHttpClient, which are used in Retrofit. A simple implementation looks like this:

We just created the AuthenticationPlugin class, which holds the key logic for adding a value to the header. As a constructor parameter, we pass SettingsRepository, which can manage storing and updating our token. It can be any implementation you want that performs this task. You would just provide that class through your Dependency Injection framework.

The key logic is specified here, where we add a value to the header.

onRequest { request, _ ->
request.headers.append(TOKEN, token)
}

We just need to install our plugin for the HttpClient. You can do that in the Ktor configuration block:

HttpClient {

install(get<AuthenticationPlugin>().createPlugin())
}

It is the simplest way to manage your credentials during requests. You can modify it to suit your requirements or even simplify it. You can find more inspiration for this in the official documentation.

I’d be happy to receive your feedback on this article. Feel free to write your comments here, share it with friends, or simply like it. I enjoy sharing my knowledge; you can find more useful content on my LinkedIn page, on X, in Medium or Mastodon.

If you’d like to buy me a coffee, you can do so through the service.

Thank you for your time, and see you in the next post!

--

--

Yauhen Slizh

Android/Flutter/KMM developer, writer and speaker. I explore this world and share my insights. I enjoy new opportunities and solving complex problems.