Skip to content

Instantly share code, notes, and snippets.

@Kiolk
Last active October 6, 2024 13:31
Show Gist options
  • Save Kiolk/07705dcb9f406c6f508a138113b004bd to your computer and use it in GitHub Desktop.
Save Kiolk/07705dcb9f406c6f508a138113b004bd to your computer and use it in GitHub Desktop.
A simple way to set a token for requests using Ktor
import io.ktor.client.plugins.api.ClientPlugin
import io.ktor.client.plugins.api.createClientPlugin
class AuthenticationPlugin(private val settingsRepository: SettingsRepository) {
fun createPlugin(): ClientPlugin<Unit> {
val token = settingsRepository.getToken()
return createClientPlugin(PLUGIN_NAME) {
onRequest { request, _ ->
request.headers.append(TOKEN, token)
}
}
}
private companion object {
const val TOKEN = "token"
const val PLUGIN_NAME = "AuthenticationPlugin"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment