authenticateWith

fun <P : Any, C, S : AuthenticationScheme<P, C>> Route.authenticateWith(scheme: S, onUnauthorized: UnauthorizedHandler? = null, build: context(PrincipalContext<P>, C) Route.() -> Unit): Route(source)

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

Report a problem

Parameters

scheme

typed authentication scheme used for this route.

onUnauthorized

optional route-level failure handler. When null, the scheme-level handler or provider challenge is used.

build

route builder with C available as a context parameter.


fun <P : Any, R : AuthenticationRole, C, S : AuthenticationScheme<P, C>> Route.authenticateWith(scheme: AuthenticationSchemeWithRoles<P, R, C, S>, roles: Set<R>? = null, onUnauthorized: UnauthorizedHandler? = null, onForbidden: ForbiddenHandler<P, C, R>? = null, build: context(PrincipalContext<P>, C, RolesContext<P, R>) Route.() -> Unit): Route(source)

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

Report a problem

Parameters

scheme

role-based typed authentication scheme.

roles

roles required to enter this route when the request is authenticated, or null to skip role enforcement while still resolving roles for authenticated callers.

onUnauthorized

optional route-level handler invoked when authentication fails.

onForbidden

optional route-level handler invoked when the principal lacks required roles.

build

route builder with RolesContext and the base scheme context available as context parameters.