Created
May 20, 2022 07:38
-
-
Save sproctor/d029e0fb833ce1eefb760e383fdbc481 to your computer and use it in GitHub Desktop.
SecretAuthenticationProvider for Ktor 1.6.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.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