kotlin - 设置 Ktor 验证关闭路由

标签 kotlin ktor

我想向我的 Ktor 服务器添加关闭路由,但我需要它来要求身份验证。

我正在尝试将关闭网址放入经过身份验证的路由中,如下所示:

// 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()
}

关于kotlin - 设置 Ktor 验证关闭路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69714863/

相关文章:

intellij-idea - Ktor - 从插件快速启动新项目抛出错误

android - 代码@TypeConverterAnnotation 是什么意思?

spring-boot - Kotlin - 数据类实体抛出 StackOverflowError

kotlin - 如何在 ktor http 客户端记录请求?

kotlin - 如何在 ktor 中创建可重用的拦截器?

kotlin - 无法在 kotlin 多平台移动版中导入依赖项

java - 从 Java 转换到 Kotlin 时出错。错误 - org.gradle.api.tasks.TaskExecutionException : Execution failed for task ':app:compileDebugKotlin'

Kotlin ,IntelliJ : math operator not working

android - 如何修复由目的地引起的膨胀错误不是此 NavGraph 的直接子级