authenticateWith
Creates a child route protected by scheme.
The provider is registered in Authentication when this route is created. Inside build, use principal to access the authenticated caller as P without casting. The first use of a provider registers it lazily; later uses of the same provider object reuse that registration. A different provider with the same name is rejected.
val userAuth = basic<User>("user-auth") {
validate { credentials -> findUser(credentials.name, credentials.password) }
}
routing {
authenticateWith(userAuth) {
get("/me") {
call.respondText(call.principal.name)
}
}
}Parameters
typed authentication scheme used for this route.
optional route-level failure handler. When null, the scheme-level handler or provider challenge is used.
route builder with C available as a context parameter.
Creates a child route protected by scheme and the required roles.
Authentication failures are handled as in authenticateWith. If authentication succeeds but the resolved roles do not include every required role, the forbidden handler is invoked. Route-level onForbidden takes precedence over AuthenticationSchemeWithRoles.forbiddenHandler on scheme.
val adminAuth = userAuth.withRoles { user ->
redis.getUserRoles(user.id) // suspend lookup from Redis or database
}
authenticateWith(adminAuth, roles = setOf(Role.Admin)) {
get("/admin") {
val user = call.principal
call.respondText("${user.name}:${user.roles.joinToString(",") { it.name }}")
}
}Parameters
role-based typed authentication scheme.
roles required to enter this route when the request is authenticated, or null to skip role enforcement while still resolving roles for authenticated callers.
optional route-level handler invoked when authentication fails.
optional route-level handler invoked when the principal lacks required roles.
route builder with RolesContext and the base scheme context available as context parameters.