The Ktor authentication plugin allows you to create multiple authorizations and give them different names. Let's create two form authentications as follows:
install(Authentication) {
form("myFormAuth") {
userParamName = "username"
passwordParamName = "password"
validate { credentials ->
if (credentials.name == "Admin" && credentials.password == "2425") {
UserIdPrincipal(credentials.name)
} else {
null
}
}
challenge {
call.respondRedirect("/auth")
}
}
form("myFormAuth2") {
userParamName = "username"
passwordParamName = "password"
validate { credentials ->
if (credentials.name == "Admin2" && credentials.password == "1213") {
UserIdPrincipal(credentials.name)
} else {
null
}
}
challenge {
call.respondRedirect("/auth")
}
}
}What happens if we apply these authorizations to one page?
authenticate("myFormAuth") {
authenticate("myFormAuth2") {
post("/page") {
call.respondText("Protected content! Name: ${call.principal<UserIdPrincipal>()?.name}")
}
}
}
get("/page") {
call.respondRedirect("/auth")
}
get("/auth") {
val formHtml = """
<form action="/page" method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" value="Auth">
</form>
""".trimIndent()
call.respondText(formHtml, ContentType.Text.Html)
}Open the IDE and check the result yourself.