Skip to content

Instantly share code, notes, and snippets.

@sproctor
Created May 20, 2022 07:38
Show Gist options
  • Save sproctor/d029e0fb833ce1eefb760e383fdbc481 to your computer and use it in GitHub Desktop.
Save sproctor/d029e0fb833ce1eefb760e383fdbc481 to your computer and use it in GitHub Desktop.
SecretAuthenticationProvider for Ktor 1.6.x
import io.ktor.application.*
import io.ktor.auth.*
import io.ktor.request.*
class SecretAuthenticationProvider internal constructor(config: Configuration) : AuthenticationProvider(config) {
internal val key: (ApplicationCall) -> String? = config.key
internal val expectedKey: String? = config.expectedKey
class Configuration internal constructor(name: String?) : AuthenticationProvider.Configuration(name) {
internal var key: (ApplicationCall) -> String? = { call -> call.request.header("secret") }
internal var expectedKey: String? = null
internal fun build() = SecretAuthenticationProvider(this)
}
}
fun Authentication.Configuration.secret(
name: String? = null,
configure: SecretAuthenticationProvider.Configuration.() -> Unit
) {
val provider = SecretAuthenticationProvider.Configuration(name).apply(configure).build()
provider.pipeline.intercept(AuthenticationPipeline.RequestAuthentication) {
val expectedKey = provider.expectedKey ?: throw Exception("No key provided")
if (expectedKey != provider.key(call)) {
throw AuthenticationException()
}
}
register(provider)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment