Home > Back-end >  Pass custom object to authenticated routes
Pass custom object to authenticated routes

Time:04-20

I was wondering if there was a way to configure the Authentication plugin so that I can pass some params (e.g. a user object) to my route handlers (similar to how UserIdPrincipal is passed in).

As an example, it might look something like this

    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
                }
            }
        }
    }

then in my routes, I could do something like

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

CodePudding user response:

You can implement the Principal interface for your User class to receive it in a route. Here is an example:

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
  • Related