orAnonymous
Returns a scheme that accepts anonymous requests when no credentials are provided.
Requests without credentials receive the principal produced by fallback. Requests with invalid credentials still fail authentication. Use the returned scheme with authenticateWith and read principal inside the route block.
Combining this scheme with authenticateWithOptional is allowed but redundant: requests without credentials already receive the anonymous principal, so principalOrNull is not null in that case.
interface Identity
data class AuthenticatedUser(val id: String) : Identity
data class GuestUser(val label: String = "guest") : Identity
val auth = basic<AuthenticatedUser>("users") {
validate { credentials -> findUser(credentials) }
}.orAnonymous { GuestUser() }
routing {
authenticateWith(auth) {
get("/feed") {
when (val user = call.principal) {
is AuthenticatedUser -> call.respondText("auth:${user.id}")
is GuestUser -> call.respondText("guest:${user.label}")
}
}
}
}Return
a scheme that produces CP for authenticated and anonymous callers.
Parameters
creates the anonymous principal when no credentials are present.
Type Parameters
authenticated principal type produced when credentials are valid.
anonymous principal type returned by fallback.
common principal type shared by authenticated and anonymous principals.