DEV Community

Lahiru Jayawickrama
Lahiru Jayawickrama

Posted on • Originally published at Medium on

Token refresh implementation with Ktor in Kotlin Multiplatform Mobile

Hey everyone, This is a short step-by-step guide for integrating a token refresh implementation with Ktor in Kotlin Multiplatform Mobile. Ktor offers an easy and straightforward approach to implementing a token refresh feature and managing the lifecycle of tokens. Without any further delay, let’s dive right in.

In this example, I will also be using Koin DI framework to get HttpClientEngine (platform-specific engine for processing network requests) and a secure store for storing and retrieving tokens (called UserManager).

Prerequisites

Kotlin Multiplatform Mobile with Koin

ktor

Napier

Add dependencies

Implementation

First we will assume that we have configured Koin DI for our KMM project. Then we will configure the platform specific Ktor HttpClientEngine with OkHttp for Android and Darwin for IOS.

In commonMain define your expected declaration for HttpClientEngine.

In AndroidMain , define your platform-specific actual declaration for the HttpClientEngine.

In IosMain, define your platform-specific actual declaration for the HttpClientEngine.

Then add your declaration to the startKoin function.

Token Refresh

Our next step will be to configure the token refresh feature using the refreshTokens ktor API.

Full HttpClient configuration,

Accordingly, what this code does is. A request will be made with a token to the protected API. API will respond with a 401 unauthorized response if the token is expired, and this will trigger the refreshTokens block to retrieve new tokens. Once the token has been retrieved, it will request the same protected API that previously responded with a 401 unauthorized response.

Code Snippets — https://gist.github.com/stargatex/7678d15a6e7bef0b3cf1262f38a7a31d

I hope you found this useful. Until next time 🙏 👋

Top comments (0)