Skip to content

Instantly share code, notes, and snippets.

@sproctor
Created May 20, 2022 07:35
Show Gist options
  • Save sproctor/de2bfa74ef119f34fffd533bed99c88b to your computer and use it in GitHub Desktop.
Save sproctor/de2bfa74ef119f34fffd533bed99c88b to your computer and use it in GitHub Desktop.
SecretAuthenticationProvider for Ktor 2.x
import io.ktor.serialization.*
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.request.*
class SecretAuthenticationProvider internal constructor(config: Config) : AuthenticationProvider(config) {
internal val key: (ApplicationCall) -> String? = { call -> call.request.header("secret") }
private val expectedKey: String = config.expectedKey ?: throw Exception("No key provided")
class Config internal constructor(name: String?) : AuthenticationProvider.Config(name) {
internal var expectedKey: String? = null
internal fun build() = SecretAuthenticationProvider(this)
}
override suspend fun onAuthenticate(context: AuthenticationContext) {
val secret = key(context.call)
if (secret != expectedKey) {
throw AuthenticationException()
}
}
}
fun AuthenticationConfig.secret(
name: String? = null,
configure: SecretAuthenticationProvider.Config.() -> Unit
) {
val provider = SecretAuthenticationProvider.Config(name).apply(configure).build()
register(provider)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment