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

Report a problem

Parameters

scheme

typed authentication scheme used for this route.

onUnauthorized

optional route-level failure handler invoked when credentials are present but invalid.

build

route builder with C available as a context parameter.


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

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

Report a problem

Parameters

scheme

role-based typed authentication scheme.

roles

roles required 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 credentials are present but invalid.

onForbidden

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

build

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