kotlin - 设置 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
?)
不幸的是,文档没有提供有关如何使关闭路由经过身份验证的任何提示。关于如何确保不只是任何人都可以调用关闭路由并关闭我的服务器的任何想法?
解决方案
该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()
}
推荐阅读
- c - 使用联合和堆的类型双关语
- macos - 如何将已经运行的二进制文件设置为在启动时运行
- javascript - jquery“.load”内容的window.history.back()?
- sql-server - 将空格添加到带有 Caps 的 Camelcase
- python - 在 tkinter 中更改滚动条的大小(使用网格布局)
- mysql - 编写此代码的另一种方法是什么?SQL中的任何快捷方式?
- php - 无法从表单中获取 $_GET 值
- cypress - 单击主窗口上的链接后如何验证元素在新窗口中的显示
- macos - macOS 上的堆栈预留大小
- asynchronous - 异步等待 F# 中的键?