How-to
Website
Web app
Sign in with a session cookie
A token kept in the page can be read by any script that reaches it. To sign a reader in without holding a token at all, let the server set a session cookie, describe the service with credentials: .sameOrigin, and keep the signed-in user in a store:
Needs: a server that answers the /api endpoints the api block names and sets the session cookie. The code declares type User and an app, as the starter does: paste it into a new project, replacing src/App.wf and the starter's src/stores/auth.wf, and deleting src/pages/Profile.wf, which reads the starter's AuthStore.
type User { id: String, name: String }
type Credentials { email: String, password: String }
/// Why signing in can be refused.
enum SignInError {
unauthorized(problem: Problem) on 401
http(error: HttpError)
}
api Auth(base: "/api") {
credentials: .sameOrigin
get me at "me" -> User!
post signIn(body: Credentials) at "signIn" -> User ! SignInError
post signOut at "signOut" -> !
}
store Session {
state user: User? = null
state checked = false
derived signedIn = user != null
action load() {
match await Auth.me() {
.ok(u) { user = u }
.err(_) { user = null }
}
checked = true
}
action signIn(email: String, password: String) -> ! SignInError {
user = try await Auth.signIn(body: Credentials(email: email, password: password))
navigate("/account")
}
action signOut() -> ! {
try await Auth.signOut()
user = null
Auth.me.invalidate()
navigate("/")
}
}
page SignIn(path: "/sign-in", title: "Sign in", description: "Sign in to your account.", noindex: true) {
state email = ""
state password = ""
state problem = ""
validate email { required email }
validate password { required }
action send() {
problem = ""
match await Session.signIn(email, password) {
.ok { }
.err(.unauthorized(_)) { problem = "That email and password do not match." }
.err(.http(e)) { problem = e.message }
}
}
Heading("Sign in").h1
if problem != "" { Alert(problem).danger }
Form(bind: form) {
on submit { send() }
Input(bind: email, label: "Email").email
Input(bind: password, label: "Password").password
Button("Sign in", type: .submit, disabled: send.pending).primary
}
}
page Account(path: "/account", title: "Your account", description: "Your account.", guard: !Session.checked || Session.signedIn, redirect: "/sign-in") {
use Session
// The guard is read when the route opens, which on a reload is before
// `load` has answered; this sends the reader on once it has.
effect { if Session.checked && !Session.signedIn { navigate("/sign-in") } }
Heading("Your account").h1
if !Session.checked { Spinner }
if let u = Session.user {
Text("Signed in as {u.name}")
Button("Sign out") { on click { Session.signOut() } }
}
}
The app asks the server who is signed in once, when the site opens, in src/App.wf:
app {
use Session
Session.load()
Router
}
How it works
Authdescribes the service.credentials: .sameOriginsends the session cookie with every call, so the page holds no token.SignInErrornames what a refused sign-in answers,on 401, and keepshttpfor every other failure.- The
Sessionstore holds the user, ornull, andsignedInis derived from it.loadasks the server who is signed in,signInandsignOutcall the service and move the reader on withnavigate. - The server sets the cookie when a sign-in succeeds, with a header such as
Set-Cookie: session=…; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=1209600.HttpOnlykeeps it from every script,SameSite=Laxfrom another site's form, andSecureoff plaintext connections. Auth.me.invalidate()on sign-out drops what the endpoint cached, and anyresourceover it asks again, so the next reader of the tab is not shown the last one's. Do the same for every endpoint whose answer is one reader's: an answer cached under oneAuthorizationheader is never served for another, but a cookie cannot be read, so the cache cannot tell one cookie's reader from the next.- The
SignInpage validates its two fields and matches the result ofSession.signIn, so a wrong password shows anAlertinstead of throwing.send.pendingdisables the button while the request runs, andnoindex: truekeeps the page out of search results. Session.load()at the top ofappruns once, when the site opens: a reader who comes back with a session cookie is signed in again, andcheckedturns true when the server has answered either way.- The
Accountpage has a guard. A guard is read once, when the route opens, so it lets the page through whilecheckedis still false, and theeffectsends a signed-out reader to/sign-inas soon as the answer arrives. Until then the page shows aSpinner.
The session is an httpOnly cookie the server sets, so the page never holds a token. guard: hides the page from a reader who is signed out, and the server still checks every request (Security).