Created
May 20, 2022 07:35
-
-
Save sproctor/de2bfa74ef119f34fffd533bed99c88b to your computer and use it in GitHub Desktop.
SecretAuthenticationProvider for Ktor 2.x
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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