我想知道是否有一种方法来配置认证插件,以便我可以传递一些参数(例如用户对象)到我的路由处理程序(类似于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
类实现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