Skip to content

Auth sessions

The login session and the middleware that resolves it.

rn_forge.fastapi.auth.sessions

The login session, kept in an rn-forge-auth :class:~rn_forge.auth.SessionStore.

The session ID travels in the __Host-session cookie. Every store call is synchronous; :class:Sessions methods are blocking and async code runs them in the thread pool. :class:SessionMiddleware resolves the session once per request and keeps its cookie current.

GET requests to the paths in untouched_paths read the session without extending it; every other request moves the idle expiry forward.

The middleware also runs the :class:~rn_forge.fastapi.auth.csrf.CsrfProtection check on an unsafe request that carries the session cookie, or that goes to the password-login path, so the application's own session-authenticated routes are protected as well as the /auth routes. A request with no session cookie reaches the application unchecked.

The cookie that carries the session ID.

ActiveSession(info, context) dataclass

A session with its account's current authorization context.

Attributes:

Name Type Description
info SessionInfo

The session's content.

context AuthorizationContext

The account's authorization context.

SessionMiddleware(app, *, sessions, untouched_paths=('/auth/session',), login_path='/auth/login/password', csrf_exempt_prefixes=('/auth/backchannel-logout/',))

Resolve the login session once per request and keep its cookie current.

The session is available through :func:active_session. Every request except a GET to untouched_paths extends the idle expiry and refreshes the cookie's Max-Age; a request whose cookie names no valid session or anonymous session gets the cookie cleared, unless its response sets the cookie itself.

An unsafe request is then checked with sessions.csrf when it carries the session cookie, whether it names a live session, a live anonymous session or nothing known, or when its path is login_path, which a browser can reach with no cookie. A failure is answered with the 403 csrf-failed problem. A request to a path under csrf_exempt_prefixes is not checked.

Parameters:

Name Type Description Default
app ASGIApp

The wrapped ASGI application.

required
sessions Sessions

Reads and extends the sessions.

required
untouched_paths Collection[str]

Paths whose GET requests do not extend the session.

('/auth/session',)
login_path str

The password-login path, checked even with no session cookie.

'/auth/login/password'
csrf_exempt_prefixes Collection[str]

Path prefixes whose requests skip the CSRF check: the back-channel logout routes, which carry a signed token.

('/auth/backchannel-logout/',)

Sessions(*, store, contexts, replay, csrf, idle_timeout, absolute_timeout, debug=False, clock=_utc_now)

Starts, reads, rotates and ends login sessions.

Parameters:

Name Type Description Default
store SessionStore

Holds the sessions.

required
contexts AuthorizationContextProvider

Supplies the account's current context for the checks.

required
replay ReplayStore

Says which (issuer, sid) pairs are revoked.

required
csrf CsrfProtection

Holds each session's CSRF token and checks unsafe requests.

required
idle_timeout timedelta

How long a session may sit unused.

required
absolute_timeout timedelta

How long a session lives whatever its use.

required
debug bool

Allow in-memory stores.

False
clock Callable[[], datetime]

Returns the current time, aware.

_utc_now

Raises:

Type Description
RuntimeError

debug is false and store, replay or the CSRF store is held in process memory.

Delete the session cookie on response.

csrf_state(cookie_id, active)

The CSRF key and stored token of a request.

Parameters:

Name Type Description Default
cookie_id str | None

The session ID from the cookie.

required
active ActiveSession | None

The session that ID names, if it names one.

required

Returns:

Type Description
str | None

The key the token is stored under and the token. The key is

str | None

None when the cookie names neither a session nor a live

tuple[str | None, str | None]

anonymous session; the token is None when none is stored.

end(session_id)

Delete the session or anonymous session with ID session_id, with its token.

ensure_csrf(cookie_id, active)

Return the request's CSRF token, minting a session or anonymous one if needed.

Returns:

Type Description
str

The token, and the ID of a new anonymous session when one was

str | None

started, which the caller must send as the session cookie.

now()

The current time, aware.

read(session_id, *, touch=True)

Return the session with ID session_id, or None when there is none.

A session past its absolute timeout, whose recorded version differs from its account's, whose account is inactive, or whose session_ref is revoked, is deleted and read as absent.

Parameters:

Name Type Description Default
session_id str | None

The session ID from the cookie.

required
touch bool

Move the idle expiry forward. False reads without extending the session.

True

rotate(session_id)

Move the session to a new ID; the old ID is unreadable afterwards.

The CSRF token moves with the session.

Returns:

Type Description
str | None

The new session ID, or None when the session is absent.

session_id(request) staticmethod

The session ID the request's cookie carries, if any.

Set the cookie that carries an anonymous session's ID.

Set the session cookie on response.

start(info, *, previous=None)

Store info under a new session ID with a new CSRF token.

The session or anonymous session previous is deleted with its token.

Returns:

Type Description
tuple[str, str]

The new session ID and its CSRF token.

start_anonymous()

Start a short-lived anonymous session that holds only a CSRF token.

Returns:

Type Description
tuple[str, str]

The anonymous session ID and its CSRF token.

active_session(request)

The request's session as :class:SessionMiddleware resolved it.

Returns:

Type Description
ActiveSession | None

The session, or None when the request has none.

Raises:

Type Description
RuntimeError

:class:SessionMiddleware is not installed.

refuse_in_memory(*, session_store=None, replay_store=None, transaction_store=None, csrf_store=None, rate_limiter=None)

Refuse stores held in process memory, which processes do not share.

Raises:

Type Description
RuntimeError

A given store is an in-memory store.

request_session(request)

The (session_id, session) the middleware resolved, or None without it.

rotate_session(request) async

Give the request's session a new ID and keep its content.

Call it after a change of the account's privileges, so a session ID that was seen before the change is useless afterwards. The middleware sets the new cookie on the response. A request with no session is left alone.

Raises:

Type Description
RuntimeError

:class:SessionMiddleware is not installed.