authenticateWithOptional
Creates a child route where authentication is optional.
Requests without credentials enter the route and expose null from principalOrNull. Requests with invalid credentials still invoke onUnauthorized or the scheme-level failure handler.
authenticateWithOptional(userAuth) {
get("/feed") {
val user = call.principalOrNull
call.respondText(user?.name ?: "guest")
}
}Parameters
typed authentication scheme used for this route.
optional route-level failure handler invoked when credentials are present but invalid.
route builder with C available as a context parameter.
Creates a child route where role-based authentication is optional.
Requests without credentials enter the route and expose null from principalOrNull. Requests with invalid credentials invoke onUnauthorized or the scheme-level failure handler. When a caller is authenticated, required roles are enforced: missing roles invoke onForbidden or the scheme-level forbidden handler. Requests without credentials skip role checks and enter the route with principalOrNull == null. Use required authenticateWith when every caller must authenticate and satisfy roles.
authenticateWithOptional(adminAuth, roles = setOf(Role.Admin)) {
get("/admin") {
val user = call.principalOrNull
if (user == null) {
call.respondText("anonymous")
} else {
call.respondText("${user.name}:${user.roles.joinToString(",") { it.name }}")
}
}
}Parameters
role-based typed authentication scheme.
roles required when the request is authenticated, or null to skip role enforcement while still resolving roles for authenticated callers.
optional route-level handler invoked when credentials are present but invalid.
optional route-level handler invoked when the principal lacks required roles.
route builder with the base scheme context and RolesContext available as context parameters.