withRoles
Creates a role-based scheme from this typed authentication scheme.
Use this extension to add authorization on top of an existing typed authentication scheme. After the base scheme authenticates a request, resolveRoles maps the principal to the roles held by that principal. Route handlers then declare which roles are required via authenticateWith.
Authentication and authorization fail separately:
The base scheme handles missing or invalid credentials.
Authenticated principals that lack any required role invoke onForbidden (HTTP 403 by default).
Inside role-protected routes, use principal and roles on the principal.
enum class Role : AuthenticationRole {
User, Admin
}
val userAuth = basic<User>("users") {
validate { credentials -> findUser(credentials) }
}
val roleAuth = userAuth.withRoles { user ->
redis.getUserRoles(user.id) // suspend lookup from Redis or database
}
routing {
authenticateWith(roleAuth, roles = setOf(Role.Admin)) {
get("/admin") {
val user = call.principal
call.respondText("${user.name}:${user.roles.joinToString { it.name }}")
}
}
}Return
a AuthenticationSchemeWithRoles that performs role checks after authentication.
Parameters
handler invoked when authentication succeeds, but the principal does not have every role required by the route. Receives the set of roles that the route demanded. Defaults to responding with HttpStatusCode.Forbidden. A route-level ForbiddenHandler passed to authenticateWith overrides this handler for that route.
function that maps the authenticated principal to the roles available for authorization. The receiver is the current RoutingContext; use it to load roles from Redis, a database, or another external store.
Type Parameters
the principal type produced by the base scheme.
the role type used for authorization checks.