设置Ktor认证关闭路由



我想添加一个关机路由到我的Ktor服务器,但我需要它需要身份验证。

我正在尝试将关闭url放在我的身份验证路由中,如下所示:

// application.conf
ktor {
deployment {
port = 8080
host = 127.0.0.1
shutdown.url = "/shutdown"
}
}
// Application.kt
routing {
root()

authenticate("authenticated-routes") {
test1()
test2()
shutdown()
}
}
// Routes.kt
fun Route.shutdown() {
get("/shutdown") {
// shutting down
}
}

但不知何故,关闭路由不需要关闭服务器的身份验证(与配置重写在Routes.kt中定义的路由有关?)

不幸的是,文档没有给出任何关于如何使关闭路由验证的提示。关于如何确保不是任何人都可以调用shutdown路由并关闭我的服务器,有什么想法吗?

ShutDownUrl插件与Routing没有任何关系,这就是为什么您不能将其与Authentication插件集成。为了解决您的问题,您可以手动创建ShutDownUrl类的实例,并在可能需要身份验证的路由中执行doShutdown方法。下面是一个例子:

import io.ktor.application.*
import io.ktor.auth.*
import io.ktor.response.*
import io.ktor.routing.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
fun main() {
val shutdown = ShutDownUrl("") { 1 }
embeddedServer(Netty, port = 3333) {
install(Authentication) {
basic {
realm = "Access for shutting the server down"
validate { credentials ->
if (credentials.name == "jetbrains" && credentials.password == "foobar") {
UserIdPrincipal(credentials.name)
} else {
null
}
}
}
}
routing {
get("/") {
call.respondText { "hello" }
}
authenticate {
get("/shutdown") {
shutdown.doShutdown(call)
}
}
}
}.start()
}

最新更新