livery_auth_session (livery v0.2.0)
View SourceSigned session-cookie middleware.
Reads a cookie, verifies its HMAC-SHA256 signature against a shared
secret, decodes the JSON payload, and stores it on the request as
meta(session, Data) (read it back with livery_ext:session/1).
The cookie is stateless: the signed payload travels with the
client, so no server-side session store is needed.
State:
{livery_auth_session, #{
secret => <<"a long random secret">>, %% required
name => <<"session">>, %% cookie name, default
meta_key => session, %% meta key, default
required => false %% default false
}}A missing cookie is allowed through when required => false (the
default); the handler sees no session meta. A present but
tampered or expired cookie is always rejected with 401.
Issue and clear cookies from a handler with sign/2 plus
set_cookie_header/2 and clear_cookie_header/1:
login(Req) ->
Value = livery_auth_session:sign(#{<<"uid">> => 42},
#{secret => Secret, max_age => 3600}),
Hdr = livery_auth_session:set_cookie_header(Value,
#{max_age => 3600}),
R = livery_resp:redirect(303, <<"/">>),
livery_resp:with_header(element(1, Hdr), element(2, Hdr), R).
Summary
Functions
Build a Set-Cookie header that expires the session cookie.
Build a Set-Cookie header carrying a signed value.
Sign a session payload into a cookie value.
Verify a cookie value and return its payload map.
Types
Functions
-spec call(livery_req:req(), livery_middleware:next(), map()) -> livery_resp:resp().
Build a Set-Cookie header that expires the session cookie.
Build a Set-Cookie header carrying a signed value.
Attributes come from Opts: path (default <<"/">>),
http_only (default true), secure (default true),
same_site (default <<"Lax">>), max_age, domain.
Sign a session payload into a cookie value.
Data is any JSON-encodable map. With max_age (seconds) an exp
claim is embedded and enforced by verify/2. Returns
base64url(payload) "." base64url(hmac).
-spec verify(binary(), map()) -> {ok, map()} | {error, error_reason()}.
Verify a cookie value and return its payload map.
Checks the HMAC signature in constant time and, if present, the
exp claim. Errors: malformed, bad_signature, expired.