Auth routes
The /auth HTTP surface, its sessions, CSRF protection, rate limits and audit
events. See the Auth guide.
Routes
rn_forge.django.auth.routes
The shared HTTP auth surface (/auth/...) as Django views and a URLconf.
Mount it with :func:auth_urlpatterns::
urlpatterns = [*auth_urlpatterns(config), ...]
The project supplies django.contrib.sessions and its middleware. The
identity providers, account resolver and authorization context provider are
:mod:rn_forge.auth objects the project 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'](), transactions=CacheTransactionStore(), replay=CacheReplayStore(), idle_timeout=timedelta(minutes=30), absolute_timeout=timedelta(hours=12), limiter=FixedWindowLimiter(), password_client_limit=_PASSWORD_PER_CLIENT, password_account_limit=_PASSWORD_PER_ACCOUNT, callback_client_limit=_CALLBACK_PER_CLIENT)
dataclass
What :func:auth_urlpatterns 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
|
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
|
return_to_prefixes |
Sequence[str]
|
Path prefixes a |
default_return_to |
str
|
Where a password login lands, which has no
|
error_route |
str
|
The SPA route a failed callback redirects to, with an
|
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. |
transactions |
TransactionStore
|
Holds logins between redirect and callback. |
replay |
ReplayStore
|
Holds replayed token IDs and revoked |
idle_timeout |
timedelta
|
How long a session may sit unused; a normal request
extends it, |
absolute_timeout |
timedelta
|
How long a session lives whatever its use, and how
long a revoked |
limiter |
FixedWindowLimiter
|
Counts hits for the rate limits, over a Django cache. |
password_client_limit |
RateLimit | None
|
Password login attempts per client address
( |
password_account_limit |
RateLimit | None
|
Password login attempts per submitted username
in a window; |
callback_client_limit |
RateLimit | None
|
Callback requests per client address in a window.
Callbacks are limited per client only; |
auth_urlpatterns(config, *, prefix='auth')
Return the URL patterns of 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, without surrounding slashes. |
'auth'
|
Returns:
| Type | Description |
|---|---|
list[URLPattern]
|
The patterns, named |
Sessions
rn_forge.django.auth.sessions
The login session, kept in django.contrib.sessions.
Every read of the session goes through :meth:Sessions.read, which enforces
the absolute timeout and the revocation checks. Idle expiry is Django's own
session expiry: a normal read pushes it forward and a read that passes
touch=False leaves it alone. SESSION_SAVE_EVERY_REQUEST must be false
(see :data:SESSION_SETTINGS).
SESSION_SETTINGS = {'SESSION_ENGINE': 'django.contrib.sessions.backends.cached_db', 'SESSION_COOKIE_NAME': SESSION_COOKIE, 'SESSION_COOKIE_SECURE': True, 'SESSION_COOKIE_HTTPONLY': True, 'SESSION_COOKIE_SAMESITE': 'Lax', 'SESSION_COOKIE_PATH': '/', 'SESSION_COOKIE_DOMAIN': None, 'SESSION_SAVE_EVERY_REQUEST': False}
module-attribute
Django settings for the session and its cookie.
Spread into your settings module: globals().update(SESSION_SETTINGS).
The __Host- cookie requires Secure, Path=/ and no Domain.
SESSION_SAVE_EVERY_REQUEST must stay false: reading the session then does
not extend it.
ActiveSession(info, context)
dataclass
A session that passed every check, with its account's current context.
Attributes:
| Name | Type | Description |
|---|---|---|
info |
SessionInfo
|
The session's content. |
context |
AuthorizationContext
|
The account's authorization context. |
Sessions(*, contexts, replay, idle_timeout, absolute_timeout)
Starts, reads and ends login sessions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
contexts
|
AuthorizationContextProvider
|
Supplies the account's current context for the checks. |
required |
replay
|
ReplayStore
|
Says which |
required |
idle_timeout
|
timedelta
|
How long a session may sit unused. |
required |
absolute_timeout
|
timedelta
|
How long a session lives whatever its use. |
required |
end(request)
Delete the request's session and its cookie.
now()
staticmethod
The current time, aware.
read(request, *, touch=True)
Return the request's session, or None when it has 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 |
|---|---|---|---|
request
|
HttpRequest
|
The request. |
required |
touch
|
bool
|
Move the idle expiry forward. |
True
|
start(request, info)
Store info under a new session ID, so a pre-login ID is never reused.
check_session_settings(*, cache_aliases)
Refuse session settings that cannot work or are unsafe.
SESSION_SAVE_EVERY_REQUEST must be false in every mode. Outside
DEBUG, the cookie settings must equal :data:SESSION_SETTINGS, the
session engine must be db or cached_db (a signed-cookie engine
cannot revoke sessions), and neither the session
cache nor cache_aliases may be Django's local-memory cache.
Raises:
| Type | Description |
|---|---|
ImproperlyConfigured
|
A setting is refused. |
rotate_session(request)
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.
CSRF
rn_forge.django.auth.csrf
CSRF protection for the session-authenticated routes.
Django's CsrfViewMiddleware checks the token and, for an Origin or
(over HTTPS) Referer header, that the origin is the request's own or in
CSRF_TRUSTED_ORIGINS. The request's scheme and host come from forwarded
headers only when SECURE_PROXY_SSL_HEADER and USE_X_FORWARDED_HOST say
so. :class:AuthCsrfMiddleware also rejects Sec-Fetch-Site: cross-site and
skips requests that carry a Bearer Authorization header.
CSRF_SETTINGS = {'CSRF_COOKIE_NAME': 'XSRF-TOKEN', 'CSRF_HEADER_NAME': 'HTTP_X_XSRF_TOKEN', 'CSRF_COOKIE_HTTPONLY': False, 'CSRF_COOKIE_SECURE': True, 'CSRF_COOKIE_SAMESITE': 'Lax', 'CSRF_COOKIE_PATH': '/', 'CSRF_COOKIE_DOMAIN': None, 'CSRF_USE_SESSIONS': False, 'CSRF_FAILURE_VIEW': CSRF_FAILURE_VIEW}
module-attribute
Django settings for the CSRF cookie and header.
Spread into your settings module with globals().update(CSRF_SETTINGS), and
add :data:CSRF_MIDDLEWARE to MIDDLEWARE. The names are Angular's
HttpClient defaults, and the cookie is readable by script, which Angular
needs to copy it into the header.
AuthCsrfMiddleware
Bases: CsrfViewMiddleware
CsrfViewMiddleware plus the cross-site and bearer rules.
process_view(request, callback, callback_args, callback_kwargs)
Check request unless it is exempt, safe, or carries credentials.
check_csrf_settings()
Refuse CSRF settings that leave the auth routes unprotected.
Always: :data:CSRF_MIDDLEWARE is installed, and the cookie and header
names, HttpOnly, CSRF_USE_SESSIONS and the failure view match
:data:CSRF_SETTINGS. Outside DEBUG, the other cookie settings must
match too. RN_FORGE_DJANGO["AUTH"]["PROBLEM_TYPE_BASE"] must be set in
every mode; csrf-failed and forbidden then differ in type.
Raises:
| Type | Description |
|---|---|
ImproperlyConfigured
|
A requirement is not met. |
csrf_failure_view(request, reason='')
Answer a CSRF rejection with the 403 csrf-failed problem.
The reason is logged and never sent.
enforce_csrf(request)
Run the check :class:AuthCsrfMiddleware runs, for a view it cannot guard.
DRF wraps its views in csrf_exempt, so a session authentication class
calls this for the requests it authenticates. A safe method, and a request
with a Bearer Authorization header, pass.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
HttpRequest
|
The Django request (a DRF request's |
required |
Raises:
| Type | Description |
|---|---|
CsrfFailed
|
The token, origin or fetch-metadata check failed. |
Stores
rn_forge.django.auth.stores
Login transactions, replay records and revoked session IDs in Django's cache.
The records are shared between processes only when the cache is, as Django's
Redis backend (the redis extra) is. The local-memory cache is for tests and
single-process development.
CacheReplayStore(*, alias='default', prefix='rn-forge:replay:')
:class:~rn_forge.auth.ReplayStore over a Django cache.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
alias
|
str
|
The cache alias in |
'default'
|
prefix
|
str
|
Prepended to every key. |
'rn-forge:replay:'
|
Attributes:
| Name | Type | Description |
|---|---|---|
alias |
The cache alias in |
is_sid_revoked(issuer, sid)
See :meth:rn_forge.auth.ReplayStore.is_sid_revoked.
record_once(key, *, ttl)
See :meth:rn_forge.auth.ReplayStore.record_once.
revoke_sid(issuer, sid, *, ttl)
See :meth:rn_forge.auth.ReplayStore.revoke_sid.
CacheTransactionStore(*, alias='default', prefix='rn-forge:tx:')
:class:~rn_forge.auth.TransactionStore over a Django cache.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
alias
|
str
|
The cache alias in |
'default'
|
prefix
|
str
|
Prepended to every key. |
'rn-forge:tx:'
|
Attributes:
| Name | Type | Description |
|---|---|---|
alias |
The cache alias in |
consume(transaction_id)
See :meth:rn_forge.auth.TransactionStore.consume.
save(transaction, *, ttl)
See :meth:rn_forge.auth.TransactionStore.save.
Rate limits
rn_forge.django.auth.rate_limit
Fixed-window rate limiting over Django's cache.
FixedWindowLimiter(*, alias='default', prefix='rn-forge:rate:', clock=time.time)
Counts hits per key in fixed windows.
The counter is cache.add followed by cache.incr, so the processes
that share the cache share the count. Windows are aligned to the clock, so
a client can use a limit twice around a window boundary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
alias
|
str
|
The cache alias in |
'default'
|
prefix
|
str
|
Prepended to every key. |
'rn-forge:rate:'
|
clock
|
Callable[[], float]
|
Returns the current time in seconds. |
time
|
Attributes:
| Name | Type | Description |
|---|---|---|
alias |
The cache alias in |
hit(scope, subject, rate)
Count one hit of subject in scope.
Returns:
| Type | Description |
|---|---|
int | None
|
|
int | None
|
window ends. |
RateLimit(limit, window)
dataclass
At most limit hits in each window.
Attributes:
| Name | Type | Description |
|---|---|---|
limit |
int
|
The hits one window allows. |
window |
timedelta
|
The length of a window. |