Skip to content

Auth routes

The /auth router and its configuration. See the Auth guide.

rn_forge.fastapi.auth.routes

The shared HTTP auth surface (/auth/...) as a FastAPI router.

Mount it with :func:auth_router::

app.add_middleware(SessionMiddleware, sessions=sessions_for(config))
app.include_router(auth_router(config))

:class:~rn_forge.fastapi.auth.sessions.SessionMiddleware resolves the session and runs the CSRF check; a router mounted without it is unprotected.

The identity providers, account resolver, authorization context provider and stores are :mod:rn_forge.auth objects the application builds and passes in :class:AuthRoutesConfig.

AuthRoutesConfig(providers, accounts, contexts, account_state, return_to_prefixes=('/',), default_return_to='/', error_route='/auth/error', post_logout_redirect='/', provider_names=dict[str, str](), backchannel=dict[str, 'BackchannelLogout'](), sessions=InMemorySessionStore(), transactions=InMemoryTransactionStore(), replay=InMemoryReplayStore(), csrf=InMemoryCsrfStore(), trusted_origins=(), trusted_proxies=(), limiter=InMemoryRateLimiter(), password_client_limit=_PASSWORD_PER_CLIENT, password_account_limit=_PASSWORD_PER_ACCOUNT, callback_client_limit=_CALLBACK_PER_CLIENT, idle_timeout=timedelta(minutes=30), absolute_timeout=timedelta(hours=12), debug=False, clock=lambda: datetime.now(UTC), problem_type_base='') dataclass

What :func:auth_router needs to serve the auth routes.

Attributes:

Name Type Description
providers Mapping[str, IdentityProvider[LoginRequest]]

The identity providers, by provider ID. A provider of kind development is served only while debug is true.

accounts AccountResolver

Links, provisions or rejects each external identity.

contexts AuthorizationContextProvider

Supplies each account's authorization context.

account_state AccountStateWriter

Persists the account's session version, which /auth/logout/all and a back-channel logout by sub bump.

return_to_prefixes Sequence[str]

Path prefixes a return_to may lie under.

default_return_to str

Where a password login lands, which has no return_to.

error_route str

The SPA route a failed callback redirects to, with an error query parameter.

post_logout_redirect str

Where the identity provider returns the browser after RP-initiated logout.

provider_names Mapping[str, str]

Display names by provider ID; the ID by default.

backchannel Mapping[str, BackchannelLogout]

Back-channel logout handlers, by provider ID.

sessions SessionStore

Holds the login sessions.

transactions TransactionStore

Holds logins between redirect and callback.

csrf CsrfStore

Holds each session's CSRF token and the anonymous sessions that protect the login request.

trusted_origins Sequence[str]

Origins, besides the request's own, that may send an unsafe request.

trusted_proxies Sequence[str]

Peer addresses or CIDR networks whose X-Forwarded-Proto, X-Forwarded-Host and X-Forwarded-For are believed.

replay ReplayStore

Holds replayed token IDs and revoked sid values.

idle_timeout timedelta

How long a session may sit unused.

absolute_timeout timedelta

How long a session lives whatever its use, and how long a revoked sid stays revoked.

limiter RateLimiter

Counts hits for the rate limits.

password_client_limit RateLimit | None

Password login attempts per client address in a window; None for no limit. The client is the peer, or the forwarded client when the peer is in trusted_proxies.

password_account_limit RateLimit | None

Password login attempts per submitted username in a window; None for no limit.

callback_client_limit RateLimit | None

Callback requests per client address in a window. Callbacks are limited per client only, because no account is known before the response is verified; None for no limit.

debug bool

Serves the development provider and accepts in-memory stores. Otherwise an in-memory sessions, transactions, replay, CSRF or rate-limit store is refused.

clock Callable[[], datetime]

Returns the current time, aware.

problem_type_base str

Prefix of the type URI of the problem responses. Required.

Raises:

Type Description
ValueError

problem_type_base is empty.

auth_router(config, *, prefix='/auth')

Return a router serving every auth route under prefix.

Method Path
GET providers
GET login/{provider}
GET callback/{provider}
GET session
POST logout
POST logout/all
POST backchannel-logout/{provider}
POST login/password

Parameters:

Name Type Description Default
config AuthRoutesConfig

The providers and collaborators the routes use.

required
prefix str

The URL prefix, with a leading slash and none at the end; empty for none.

'/auth'

Returns:

Type Description
APIRouter

The router, to pass to FastAPI.include_router.

sessions_for(config)

A :class:Sessions with the stores and timeouts of config.

Pass it to :class:~rn_forge.fastapi.auth.sessions.SessionMiddleware so the middleware and the routes of auth_router(config) agree.

Raises:

Type Description
RuntimeError

config.debug is false and a store is held in memory.