将自定义对象传递给经过身份验证的路由

Pass custom object to authenticated routes

我想知道是否有一种方法可以配置身份验证插件,以便我可以将一些参数(例如用户对象)传递给我的路由处理程序(类似于 UserIdPrincipal 的传递方式)。

例如,它可能看起来像这样

    install(Authentication) {
        basic("auth-basic") {
            validate { credentials ->
                val user = userRepo.verifyUser(credentials.name, credentials.password)
                if (user != null) {
                    // UserIdPrincipal(credentials.name) // current impl
                    user // desired
                } else {
                    log.info("Unauthorized route access with credential name: ${credentials.name}")
                    null
                }
            }
        }
    }

然后在我的路线中,我可以做类似

的事情
post("/foo") {
    val user = call.receive<User>()
}

您可以为您的 User class 实现 Principal 接口,以便在路由中接收它。这是一个例子:

fun main() {
    embeddedServer(Netty, port = 8080, host = "0.0.0.0") {
        install(Authentication) {
            basic("auth-basic") {
                realm = "Access to the '/' path"
                validate { credentials ->
                    if (credentials.name == "jetbrains" && credentials.password == "foobar") {
                        userRepo.verifyUser(credentials.name, credentials.password)
                    } else {
                        null
                    }
                }
            }
        }

        routing {
            authenticate("auth-basic") {
                get("/login") {
                    val user = call.principal<User>()
                    println("Hello ${user?.name}")
                }
            }
        }
    }.start(wait = true)
}

class User(val name: String): Principal