Chapter 50 · API authentication and permissionsCHAPTER 50
Complete six-part pre-release for review. No package is added. Missing or bad credentials now get 401 and are told to send a Bearer token, where Chapter 48 answered 403; two earlier tests change on purpose (declared in the chapter). The form template now groups checkboxes and radio buttons in a fieldset. The optional GitHub sign-in lab was not run.
Working towards: API and integrations (Chapter 54). Another program can list published events through an API and receive signed notifications when an event changes. All milestones
CHAPTER FIFTY
API authentication and permissions
Stage 6: APIs and real-time updates (Chapters 47 to 54)
Prerequisites: Chapters 9 to 49, including the Chapter 49 project with its 685 passing tests, the organizer’s events as one viewset, DRF’s strict defaults, refused attempts recorded with deny() and record(), and allauth’s re-authentication from Chapter 29
What you’ll build: personal access tokens for programs, made once on an API tokens page behind the password, stored as a hash, sent as Authorization: Bearer, limited by scopes, expiring, and revocable; 401 for missing or bad credentials; tokens refused in addresses; every change a token makes recorded with its name; the API rows of the permission matrix; and Sam’s first script
Why This Matters
Sam wants a script that runs on his laptop every night: it reads his events through the API and, later, creates next month’s drafts. Since Chapter 48 the API answers only the site’s own session, which a script cannot hold. It has no browser, no cookie, and no CSRF token, and Sam must never type his password into it. An AI agent acting for Sam has the same problem, and a worse one: whatever it holds, it might paste somewhere.
So programs need a credential of their own. It must do less than Sam’s password: read his events, perhaps change them, but never more than he chose, and never more than Sam himself may do today. It must stop working on a date, or at once when Sam revokes it. It must stay out of logs and addresses, where secrets leak most often. And when Raj asks why his event’s title changed at two in the morning, the audit trail must say “Sam, through the token nightly import”, not just “Sam”.
This chapter builds that credential, a personal access token, and makes the API ask two questions in a fixed order: who is asking, then may they do this. It also changes one answer on purpose: a request with no credentials now gets 401 and is told to send a token, where Chapter 48 answered 403.
By the end of the chapter, you will be able to:
tell authentication from authorization in an API, and explain when each of 401 and 403 is right;
design a token that is shown once, stored as a hash, compared in constant time, scoped, and expiring;
write a DRF authentication class for Authorization: Bearer, and order it with the session;
limit each viewset action to a scope with a permission class, without ever exceeding the owner’s own rights;
keep a token out of addresses, logs, and error reports, and name it in the audit trail;
build a page that makes and revokes tokens behind a second password check.
Out of scope: limits on how often a token may call (Chapter 51), signing outgoing messages (Chapter 52), an OAuth 2 server for other companies’ applications (not built; Step 9’s ADR says why), and attacking tokens on purpose (Chapter 60).
Every API request answers two questions. Authentication is “who is asking?”: a session cookie, a token, or nobody. Authorization is “may they do this?”: is Sam an organizer, does he organize this event, does this token allow changes. Otahque has answered both since Chapter 30 for its pages; DRF asks them in its own fixed order, drawn in Figure 50.1.
Figure 50.1 — Who are you, then may you.
The status codes follow the questions. 401 Unauthorized, despite its name, means “I do not know who you are”: the client sent no credentials, or bad ones, and the answer must carry a WWW-Authenticate header naming the scheme to use (RFC 9110). 403 Forbidden means “I know who you are, and the answer is no.” A program that gets 401 should fetch a new token; one that gets 403 should stop, because a new token will not help.
Under the Hood: how DRF chooses between 401 and 403
APIView.initial() runs the classes in DEFAULT_AUTHENTICATION_CLASSES in order. Each authenticate() returns a member and a credential, returns None to let the next class try, or raises AuthenticationFailed to stop at once. When no class finds anyone and a permission class refuses, handle_exception() asks the first class for authenticate_header(). If that returns a value, DRF answers 401 with it as WWW-Authenticate; if it returns nothing, as SessionAuthentication’s does, DRF answers 403. Otahque’s list has held only the session since Chapter 48, which is why a visitor got 403. Putting a class that names Bearer first turns those answers into 401, without touching a single view.
Sessions, CSRF, and why programs need something else
The site’s own pages, and the htmx parts of them since Chapter 45, call Otahque with the session cookie. The browser sends that cookie automatically, even when another site’s page triggers the request, so every write made with a session needs the CSRF token too; DRF’s SessionAuthentication checks it for any signed-in request. A script has no cookie jar and no page to read a CSRF token from. A token sent in a header has the opposite property: the browser never adds it by itself, so another site cannot make a browser send it, and no CSRF token is needed.
New Concept: a personal access token
What problem exists? A program must act for a member without the member’s password, with less power than the member, for a limited time, and in a way the member can stop.
What did people do before? Programs held the password itself, and used HTTP Basic authentication; or a site gave each member one fixed API key, stored as written, that never expired.
What is it? A personal access token is a long random secret that a member makes for one program. The site stores only a hash of it, shows the full text once, and records its scopes (what it may be used for), when it expires, when it was last used, and whether it was revoked. The program sends it in each request as Authorization: Bearer otq_..., the “bearer” scheme of RFC 6750: whoever bears it is let in, so it is guarded like a password.
Why use it? Each program gets its own token, so revoking one leaves the others working, and the audit trail can say which program did what.
Now let’s use it. Steps 3 to 7 build Otahque’s: the model, the authentication class, the scopes, and the page that makes them.
Designing the token
Three designs were compared in the plan review (Table 50.1), and the decision is recorded in ADR-008 in Step 9.
Table 50.1 — Three token designs
Design
What it stores and offers
Why not, or why
DRF's TokenAuthentication
One key per member, stored as written; no expiry or scopes
A copy of the table is every member's key
django-rest-knox 6.0.0
Hashed, expiring tokens; supports Django 6.1
No scopes; released days before this chapter
Otahque's own
otq_, an id, a secret; SHA-256 of the secret; scopes, expiry, revocation, last use
Small, and every rule is visible in one model
The token’s text has three parts: otq_, an 8-character id, and a 32-character secret, such as otq_k3v9x2ab_ followed by 32 letters and digits. The prefix lets a secret scanner, such as the one a code host runs on every push, recognise a leaked Otahque token. The id finds the row in the database, so the server never compares a secret with every stored hash. The secret is about 190 random bits from Python’s secrets module.
Under the Hood: why SHA-256 is enough here, and why compare_digest
Passwords are stored with a deliberately slow hash (Django’s PBKDF2), because people choose guessable passwords and a slow hash makes each guess expensive. A token’s secret is not chosen by a person: 190 random bits cannot be guessed however fast the hash is, so a fast hash such as SHA-256 is enough, and it keeps each API request cheap. The comparison still matters. == on two strings stops at the first difference, so in principle the time it takes says how many leading characters matched; hmac.compare_digest() takes the same time whatever the input. The token is then useless if the database is copied, because only hashes are kept, and the secret’s text exists only on the page that showed it once and wherever its owner put it.
Figure 50.2 — A token’s life.
Scopes, and the owner’s rights now
A scope names a kind of action. Otahque has four, one per kind of thing an organizer’s program does (Table 50.2). A token carries the ones its owner ticked; the site’s own session has all four.
Table 50.2 — Scopes and the actions they allow
Scope
Viewset actions
Typical program
read
list, retrieve
A dashboard of my events
write
create, partial_update
A script that makes next month's drafts
publish
publish, cancel
An agent that publishes when ready
delete
destroy (a draft)
Cleaning up test drafts
A scope never adds a right. Each request still runs event_to_manage(), which asks the event whether this member organizes it now. If Sam leaves the Organizers group, his tokens stop listing events the same day; if he is removed from one event, his tokens lose that event. A token is a narrower Sam, never a different one.
Where tokens leak
A token sent in an address, ?token=otq_..., is copied into server logs, browser history, the Referer header of the next page, and Django’s error reports. Django masks the Authorization header in an error report, because its name matches the patterns it hides, but it prints the query string as sent. So Otahque refuses any request with token or access_token in its address, with 400, and never even checks the token: the safe answer to a leaked token is to revoke it, and the error says so.
In practice: tracing an agent’s change
Situation. An organizer lets an AI agent draft events through the API, and one morning a published event’s capacity has dropped from 80 to 8.
Application. The audit record for the edit names the actor and the token, so the organizer sees the change came from “Sam via token clinic-agent”, revokes that token on the API tokens page, and the agent’s next request gets 401. The site’s pages, and Sam’s other tokens, keep working.
Consideration. The record shows which credential acted, not why: the agent’s own log, or the dry run it should have sent first (Chapter 48), explains the mistake. Ordinary audit rows are not tamper-proof; Chapter 65 deals with retention and alerts.
The page that makes tokens
Only organizers make tokens: members have nothing in the API to change, and administrators manage no events on Otahque’s own pages. The API tokens page lives under the account, at /accounts/tokens/, behind allauth’s reauthentication_required, the decorator Chapter 29 put on the organizer access page: even a signed-in member must give the password, or the second factor, again before the page opens. A token is a key that outlives the session, so a laptop left signed in for a minute must not be enough to make one. Revoking a token asks for the password again too: a program Sam relies on must not be cut off by whoever passes his desk, and the check costs Sam a moment. Each organizer may have at most five active tokens, each expiring after 7, 30, or 90 days.
Start from Chapter 49, in the folder containing manage.py, with Otahque on PostgreSQL 18, 685 passing tests, and the work committed (the last commit is “Organize the API in a viewset; generate OpenAPI”). No package is added. Two migrations are made: the token table, and a token link and three new actions on audit records. New files: the token model’s module filled in, an authentication class, a permission class, a form, the tokens page’s views and template, a small module describing tokens to the OpenAPI file, an audit middleware, a test module, ADR-008, and examples/my_events.py. The settings, the API’s views, the project’s addresses, the audit model, the profile and developers pages, My events, the form field template, the site’s script and stylesheet, the contract, the permission matrix, the OpenAPI file, and two earlier test modules change. The visible result: organizers make, copy, and revoke tokens on an API tokens page; a script lists Sam’s events with one; a visitor gets 401 and is told to send a token. The commands were checked in Windows PowerShell 5.1 and Git Bash against PostgreSQL 18.
The Custom Way
The quickest token a tutorial shows is a random string saved in a column and compared with ==:
Not added to the project
key = request.headers['Authorization'].split()[1]
user = User.objects.get(api_key=key)
It works, and it has four faults Otahque cannot accept. The column holds every member’s key as written, so a database copy is a set of keys. get() on the secret itself compares it in the database, and the error for a wrong key differs from the error for a missing header. Nothing expires or narrows the key. And nothing records which program used it. DRF’s own TokenAuthentication is a tidier version of the same design (Table 50.1). This illustration is not added to the project.
The Django Way
The Django Way, with DRF, is to answer the two questions in their own classes: an authentication class that turns a header into a member and a token, and permission classes that decide, with the model’s own methods having the last word. The token is a model like any other, made and revoked through methods that record what they did.
Step 1: Check the starting point
Terminal
uv run python manage.py test --parallel
Output
Found 685 test(s).
Creating test database for alias 'default'...
...
Ran 685 tests in ...s
OK
Terminal
git status --short
git log --oneline -1
Output
... Organize the API in a viewset; generate OpenAPI
Step 2: Ask the API who is calling
Save this as who.py beside manage.py. It calls Sam’s events three ways: with no credentials, with a made-up token, and as Sam’s browser would, with his session but no CSRF token.
who.py
"""Ask the API who is calling, three ways (Chapter 50)."""
from django.test import Client
from accounts.models import User
MINE = '/api/v1/my/events/'
def show(label, answer):
"""Print the status, the scheme asked for, the detail."""
scheme = answer.get('WWW-Authenticate', 'none')
print(f'{label}: {answer.status_code}, asks for {scheme}')
print(' ', answer.json()['detail'])
visitor = Client(HTTP_HOST='localhost')
show('no credentials', visitor.get(MINE))
show('a wrong token', visitor.get(
MINE, headers={'Authorization': 'Bearer otq_wrong'}))
browser = Client(HTTP_HOST='localhost',
enforce_csrf_checks=True)
browser.force_login(User.objects.get(email='sam@example.org'))
show('session, no CSRF', browser.post(
MINE, {}, content_type='application/json'))
Terminal
uv run manage.py shell -v 0 -c "exec(open('who.py').read())"
Output
no credentials: 403, asks for none
Authentication credentials were not provided.
a wrong token: 403, asks for none
Authentication credentials were not provided.
session, no CSRF: 403, asks for none
CSRF Failed: CSRF cookie not set.
All three are 403, and none says what to send. The made-up token was not even read: the session class does not know the Bearer scheme, so to Otahque the request has no credentials. Keep who.py; Step 4 runs it again.
Step 3: The token model
The tests first. Create api/tests/test_tokens.py; later steps add a class each to the end of it:
api/tests/test_tokens.py
"""Tokens for programs (Chapter 50).
A token is made on the API tokens page, shown once, and
stored as a hash. Sent as Authorization: Bearer, it acts
for its owner within its scopes, and a bad one is 401.
The audit trail names the token behind each change.
"""
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from django.test import RequestFactory, TestCase
from django.urls import reverse
from django.utils import timezone
from django.views.debug import SafeExceptionReporterFilter
from rest_framework.test import APIClient
from api.models import PersonalAccessToken as Token
from api.models import digest
from api.tests.test_mine import ready
from api.tests.test_writes import MINE
from audit.models import AuditEvent
from config.helpers import SAI_PASSWORD, in_group
from registrations.tests.test_registrations import verified
ALL = ['read', 'write', 'publish', 'delete']
BAD = 'otq_aaaaaaaa_' + 'b' * 32
def bearer(text):
"""Return an API client that sends text as its token."""
api = APIClient()
api.credentials(HTTP_AUTHORIZATION=f'Bearer {text}')
return api
class Tokens(TestCase):
"""Sam, an organizer, with a draft of his own."""
@classmethod
def setUpTestData(cls):
cls.sam = in_group('sam@example.org', 'Organizers')
cls.raj = in_group('raj@example.org', 'Organizers')
def setUp(self):
self.event = ready(title='Clinic')
self.event.add_organizer(self.sam)
self.address = f'{MINE}{self.event.pk}/'
def token(self, scopes=ALL, user=None):
"""Issue a token; return it and a client sending it."""
token, text = Token.issue(user or self.sam, 'agent',
scopes)
return token, bearer(text)
class IssueTests(Tokens):
"""Making a token."""
def test_shown_once_and_stored_as_a_hash(self):
token, text = Token.issue(self.sam, 'agent', ['read'])
prefix, key, secret = text.split('_')
self.assertEqual((prefix, key), ('otq', token.key))
self.assertEqual(len(secret), 32)
self.assertEqual(token.secret_hash, digest(secret))
stored = str(list(Token.objects.values()))
self.assertNotIn(secret, stored)
def test_only_organizers_may(self):
for user in (verified('sai@example.org'),
in_group('ann@example.org',
'Administrators')):
with self.subTest(user.email):
with self.assertRaises(ValidationError):
Token.issue(user, 'agent', ['read'])
def test_at_most_five_active(self):
made = [Token.issue(self.sam, f't{n}', ['read'])[0]
for n in range(5)]
with self.assertRaises(ValidationError):
Token.issue(self.sam, 'sixth', ['read'])
made[0].revoke(self.sam)
Token.issue(self.sam, 'sixth', ['read'])
def test_making_one_is_recorded(self):
token, _ = Token.issue(self.sam, 'agent', ['read'])
row = AuditEvent.objects.get(action='create_token')
self.assertEqual((row.actor, row.target_id),
(self.sam, token.pk))
test_shown_once_and_stored_as_a_hash is the design in one test: the text splits into otq, the key, and a 32-character secret, and the secret appears nowhere in the stored row.
Terminal
uv run python manage.py test api.tests.test_tokens
Output
Found 1 test(s).
ERROR: test_tokens (unittest.loader._FailedTest.test_tokens)
ImportError: Failed to import test module: test_tokens
ImportError: cannot import name 'PersonalAccessToken' from
'api.models'
(...\api\models.py)
Ran 1 test in ...s
FAILED (errors=1)
api/models.py still holds the comment startapp wrote. Replace the whole file. Its top:
api/models.py
"""Personal access tokens, for programs (Chapter 50)."""
import hashlib
import hmac
import re
import secrets
import string
from datetime import timedelta
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from django.db import models, transaction
from django.utils import timezone
from audit.models import AuditEvent, record
# otq_, an id of 8, then a secret of 32: about 190 random
# bits. The prefix lets secret scanners spot a leaked one.
TEXT = re.compile(r'otq_([a-z0-9]{8})_([A-Za-z0-9]{32})')
MOST_ACTIVE = 5
DAYS = [7, 30, 90]
# Who may make tokens: organizers, who may add and change
# events (Chapter 30's group), not administrators.
ORGANIZER = ['events.add_event', 'events.change_event']
def random_text(length, alphabet):
"""Return length characters chosen by secrets."""
return ''.join(secrets.choice(alphabet)
for _ in range(length))
def digest(secret):
"""Return the SHA-256 of secret, in hexadecimal.
A slow password hash protects guessable secrets; this
one is random and long, so a fast hash is enough.
"""
return hashlib.sha256(secret.encode()).hexdigest()
class TokenQuerySet(models.QuerySet):
"""Ways to narrow a set of tokens."""
def active(self):
"""Return tokens not revoked and not yet expired."""
return self.filter(revoked_at__isnull=True,
expires_at__gt=timezone.now())
and, after two blank lines, the model:
api/models.py
class PersonalAccessToken(models.Model):
"""A credential a member gives a program, not a password.
Only a hash of its secret is stored; the full text is
shown once, when it is made. It acts for its owner,
never with more than the owner may do now, and only
for the scopes it carries.
"""
class Scope(models.TextChoices):
"""What a token may be used for, one per action."""
READ = 'read', 'Read your events'
WRITE = 'write', 'Create drafts and change events'
PUBLISH = 'publish', 'Publish and cancel events'
DELETE = 'delete', 'Delete drafts'
owner = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE,
related_name='tokens',
)
name = models.CharField(max_length=60)
key = models.CharField(max_length=8, unique=True)
secret_hash = models.CharField(max_length=64)
scopes = models.JSONField(default=list)
created_at = models.DateTimeField(default=timezone.now)
expires_at = models.DateTimeField()
last_used_at = models.DateTimeField(null=True, blank=True)
revoked_at = models.DateTimeField(null=True, blank=True)
objects = TokenQuerySet.as_manager()
class Meta:
ordering = ['-created_at', '-id']
def __str__(self):
return f'{self.name} ({self.shown})'
@property
def shown(self):
"""Return the part of the token safe to show."""
return f'otq_{self.key}_…'
def is_active(self):
"""Return whether the token may still be used."""
return (self.revoked_at is None
and self.expires_at > timezone.now())
def allows(self, scope):
"""Return whether the token carries scope."""
return scope in self.scopes
@classmethod
def issue(cls, owner, name, scopes, days=90):
"""Make a token for owner; return it and its text.
Only organizers may, and at most five active each.
The owner's row is locked while counting, so two
requests at once cannot both make the fifth.
"""
if not owner.has_perms(ORGANIZER):
raise ValidationError(
'Only organizers may create tokens.')
with transaction.atomic():
get_user_model().objects.select_for_update().get(
pk=owner.pk)
if cls.objects.filter(
owner=owner).active().count() >= MOST_ACTIVE:
raise ValidationError(
'You have five active tokens. Revoke one '
'before you create another.')
secret = random_text(
32, string.ascii_letters + string.digits)
token = cls(
owner=owner, name=name,
key=random_text(
8, string.ascii_lowercase + string.digits),
secret_hash=digest(secret),
scopes=[s for s in cls.Scope.values
if s in scopes],
expires_at=timezone.now() + timedelta(days=days),
)
token.full_clean()
token.save()
record(owner, AuditEvent.Action.CREATE_TOKEN, token,
name=name, scopes=token.scopes, days=days)
return token, f'otq_{token.key}_{secret}'
@classmethod
def find(cls, text):
"""Return the token text names, or None.
The key finds the row; the secret's hash is compared
in constant time, so timing says nothing about it.
"""
found = TEXT.fullmatch(text)
if found is None:
return None
token = cls.objects.select_related('owner').filter(
key=found[1]).first()
if token is None or not hmac.compare_digest(
token.secret_hash, digest(found[2])):
return None
return token
def touch(self):
"""Note that the token was used, at most each minute.
One write per minute is enough to see a token in use,
and spares the database a write on every request.
"""
now = timezone.now()
minute_ago = now - timedelta(minutes=1)
if (self.last_used_at is None
or self.last_used_at < minute_ago):
self.last_used_at = now
type(self).objects.filter(pk=self.pk).update(
last_used_at=now)
def revoke(self, by):
"""Stop the token working from now; record who did."""
if self.revoked_at is None:
with transaction.atomic():
self.revoked_at = timezone.now()
self.save(update_fields=['revoked_at'])
record(by, AuditEvent.Action.REVOKE_TOKEN, self,
name=self.name)
issue() is the only way a token is made. It checks the organizer, locks the owner’s row so two requests at once cannot both make the fifth token (the same lock as Chapter 46’s waitlist), stores the hash, records the creation, and returns the text once. find() never looks up a secret: it finds the row by key, then compares hashes with hmac.compare_digest(). touch() notes the last use at most once a minute, so reading events does not write to the database on every request.
Common Error: returning the token from a property or __str__
A model method that rebuilds or prints the full token, for the admin or a log line, cannot exist here: only the hash is stored. If you find yourself wanting one, the design has a hole. Show shown (otq_k3v9x2ab_...) instead, which is safe anywhere.
Next, the audit trail. In audit/models.py, the first lines become:
audit/models.py
"""The audit trail: who did what, and whether allowed."""
from contextvars import ContextVar
from django.conf import settings
Add the three new actions after UNDO_CHECK_IN:
audit/models.py
# Chapter 50: tokens for programs.
MANAGE_TOKENS = 'manage_tokens', 'Open API tokens'
CREATE_TOKEN = 'create_token', 'Create an API token'
REVOKE_TOKEN = 'revoke_token', 'Revoke an API token'
the link to the token, above created_at:
audit/models.py
# Chapter 50: the token a program used, if any, so
# "Sam via token clinic-agent" can be told from Sam.
token = models.ForeignKey(
'api.PersonalAccessToken', on_delete=models.PROTECT,
null=True, blank=True, related_name='audit_events',
)
and, above record(), the context variable:
audit/models.py
# Chapter 50: the token the current request used, set by
# the API's authentication and cleared when the request
# ends (CredentialMiddleware). A context variable belongs to
# one request, even with threads or async code.
acting_token = ContextVar('acting_token', default=None)
record() itself gains a sentence and one line:
audit/models.py
def record(actor, action, target=None,
outcome=AuditEvent.Outcome.ALLOWED, **detail):
"""Add one audit row.
Call it inside the action's own transaction, so a failed
action leaves no row. Since Chapter 50 the row also
names the token the request used, read from
acting_token, so no caller has to pass it.
"""
if actor is not None and not actor.is_authenticated:
actor = None
return AuditEvent.objects.create(
actor=actor,
action=action,
outcome=outcome,
target_type=(target._meta.model_name
if target is not None else ''),
target_id=target.pk if target is not None else None,
detail=detail,
token=acting_token.get(),
)
A context variable (Python’s contextvars) holds one value per request, even when several requests run at once on threads or as async code. The authentication class of Step 4 sets it, and record() reads it, so none of the model methods that record (edit(), publish_by(), cancel_by(), delete_by(), deny(), and the rest) needs a new argument. The link uses PROTECT, as actor does: a token named in the trail cannot be deleted, only revoked.
Make both migrations, the token table first, then apply them:
Terminal
uv run python manage.py makemigrations api
uv run python manage.py makemigrations audit --name tokens
uv run python manage.py migrate
Output
Migrations for 'api':
api\migrations\0001_initial.py
+ Create model PersonalAccessToken
Migrations for 'audit':
audit\migrations\0007_tokens.py
+ Add field token to auditevent
~ Alter field action on auditevent
Operations to perform:
Apply all migrations: account, accounts, admin, api, audit,
auth, contenttypes, django_tasks_database, events, mfa,
registrations, sessions, socialaccount
Running migrations:
Applying api.0001_initial... OK
Applying audit.0007_tokens... OK
Terminal
uv run python manage.py test api.tests.test_tokens
Output
Found 4 test(s).
Creating test database for alias 'default'...
...
Ran 4 tests in ...s
OK
Step 4: Bearer authentication, first
Add the tests for the header to the end of test_tokens.py:
api/tests/test_tokens.py
class BearerTests(Tokens):
"""Authorization: Bearer, and what is refused."""
def assertRefused(self, page):
"""Check page is 401, asking for a Bearer token."""
self.assertEqual(page.status_code, 401)
self.assertEqual(page['WWW-Authenticate'],
'Bearer realm="api"')
self.assertEqual(page['Content-Type'],
'application/problem+json')
def test_a_token_reads_my_events(self):
token, api = self.token(['read'])
page = api.get(MINE)
self.assertEqual(page.status_code, 200)
titles = [e['title'] for e in page.json()['results']]
self.assertEqual(titles, ['Clinic'])
token.refresh_from_db()
self.assertIsNotNone(token.last_used_at)
def test_no_credentials_is_401(self):
self.assertRefused(APIClient().get(MINE))
def test_an_unknown_token_is_401(self):
self.assertRefused(bearer(BAD).get(MINE))
def test_the_right_id_with_a_wrong_secret_is_401(self):
token, _ = self.token()
self.assertRefused(bearer(
f'otq_{token.key}_' + 'b' * 32).get(MINE))
def test_expired_and_revoked_tokens_are_401(self):
expired, api_expired = self.token()
Token.objects.filter(pk=expired.pk).update(
expires_at=timezone.now())
revoked, api_revoked = self.token()
revoked.revoke(self.sam)
for api in (api_expired, api_revoked):
self.assertRefused(api.get(MINE))
def test_an_inactive_owner_is_401(self):
_, api = self.token()
get_user_model().objects.filter(pk=self.sam.pk).update(
is_active=False)
self.assertRefused(api.get(MINE))
def test_a_bad_token_is_not_passed_to_the_session(self):
api = bearer(BAD)
api.force_login(self.sam)
self.assertRefused(api.get(MINE))
def test_a_token_in_the_address_is_400_unchecked(self):
token, _ = self.token()
text = Token.issue(self.sam, 'leak', ALL)[1]
for address in (f'{MINE}?access_token={text}',
f'/api/v1/events/?token={text}'):
with self.subTest(address.split('?')[0]):
page = APIClient().get(address)
self.assertEqual(page.status_code, 400)
self.assertIn('never in the address',
page.json()['detail'])
self.assertFalse(Token.objects.filter(
last_used_at__isnull=False).exists())
test_a_bad_token_is_not_passed_to_the_session holds a rule that is easy to get wrong: a request that says Bearer and fails is refused, even if the same browser also has a session. Falling back would let a broken or revoked token look as if it worked.
Terminal
uv run python manage.py test api.tests.test_tokens
Output
Found 12 test(s).
Creating test database for alias 'default'...
FAIL: test_a_bad_token_is_not_passed_to_the_session
AssertionError: 200 != 401
FAIL: test_a_token_in_the_address_is_400_unchecked
AssertionError: 200 != 400
FAIL: test_a_token_in_the_address_is_400_unchecked
AssertionError: 403 != 400
... (6 more like these)
Ran 12 tests in ...s
FAILED (failures=9)
Create api/authentication.py:
api/authentication.py
"""How the API knows who is asking (Chapter 50)."""
from rest_framework import authentication, exceptions, status
from audit.models import acting_token
from .models import PersonalAccessToken
# Names a token is often sent under in a URL, by mistake.
IN_URL = ('token', 'access_token')
class TokenInURL(exceptions.APIException):
"""A token sent in the address, where logs keep it."""
status_code = status.HTTP_400_BAD_REQUEST
default_detail = ('Send the token in the Authorization '
'header, never in the address. Revoke '
'this one: it may now be in logs.')
class BearerAuthentication(authentication.BaseAuthentication):
"""Read a personal access token from Authorization.
Authorization: Bearer otq_... (RFC 6750). No header, or
another scheme, passes to the next class, the session.
A Bearer header that names no active token is refused
with 401, never passed on.
"""
keyword = 'Bearer'
def authenticate(self, request):
"""Return (owner, token), None, or refuse with 401."""
if any(name in request.query_params for name in IN_URL):
raise TokenInURL
header = authentication.get_authorization_header(
request).decode('latin-1')
scheme, _, text = header.partition(' ')
if scheme.lower() != self.keyword.lower():
return None
token = PersonalAccessToken.find(text.strip())
if token is None:
raise exceptions.AuthenticationFailed(
'The token is not valid.')
if not token.is_active():
raise exceptions.AuthenticationFailed(
'The token has expired or was revoked.')
if not token.owner.is_active:
raise exceptions.AuthenticationFailed(
'The account is not active.')
token.touch()
acting_token.set(token)
return token.owner, token
def authenticate_header(self, request):
"""Name the scheme in WWW-Authenticate, making 401s.
DRF answers 401 only if the first class names one;
otherwise a visitor gets 403.
"""
return f'{self.keyword} realm="api"'
authenticate() returns None for a request without Bearer, so the session class gets its turn; it raises AuthenticationFailed for a Bearer request that names no active token. It refuses a token in the address before reading anything else. authenticate_header() is what turns DRF’s refusals into 401.
Create audit/middleware.py, which clears the context variable when each request ends:
audit/middleware.py
"""Middleware for the audit trail (Chapter 50)."""
from .models import acting_token
class CredentialMiddleware:
"""Forget the request's token when the request ends.
The API's authentication sets acting_token; without
this, the next request on the same thread would be
recorded as made with that token.
"""
def __init__(self, get_response):
"""Keep the next handler in the chain."""
self.get_response = get_response
def __call__(self, request):
"""Start with no token; restore the old value after."""
reset = acting_token.set(None)
try:
return self.get_response(request)
finally:
acting_token.reset(reset)
Common Error: a context variable that outlives its request
Without CredentialMiddleware, the value the token set stays in the thread’s context, and the next request served by the same thread, perhaps Sam using the site in his browser, is recorded “via token nightly import”. test_the_next_request_forgets_the_token in Step 5 sends exactly that pair of requests. Setting and resetting in the same middleware, as Chapter 39’s request id does, keeps each value inside one request.
In config/settings.py, the authentication classes become:
config/settings.py
REST_FRAMEWORK = {
# Chapter 50: a program's token first, so a request with
# no credentials, or a bad one, gets 401 and is told to
# send a Bearer token; then the site's own session.
'DEFAULT_AUTHENTICATION_CLASSES': [
'api.authentication.BearerAuthentication',
'rest_framework.authentication.SessionAuthentication',
],
and the middleware list ends:
config/settings.py
'allauth.account.middleware.AccountMiddleware',
# Chapter 50: forget a request's API token when it ends.
'audit.middleware.CredentialMiddleware',
]
Terminal
uv run python manage.py test api.tests.test_tokens
Output
Found 12 test(s).
Creating test database for alias 'default'...
...
Ran 12 tests in ...s
OK
Run who.py again, then delete it:
Terminal
uv run manage.py shell -v 0 -c "exec(open('who.py').read())"
Output
no credentials: 401, asks for Bearer realm="api"
Authentication credentials were not provided.
a wrong token: 401, asks for Bearer realm="api"
The token is not valid.
session, no CSRF: 403, asks for none
CSRF Failed: CSRF cookie not set.
The first two answers now say who they are waiting for. The session without CSRF is still refused with 403: it was a known member, and the missing CSRF token is a reason to refuse, not a missing identity.
That change of answer was on purpose, and two earlier tests said otherwise. Run them with the rest of the API’s tests:
Terminal
uv run python manage.py test api config.tests.test_public
Output
Found 76 test(s).
Creating test database for alias 'default'...
FAIL: test_a_visitor_gets_403
AssertionError: 401 != 403
FAIL: test_a_visitor_is_sent_to_sign_in_elsewhere
AssertionError: 401 != 403
FAIL: test_a_visitor_is_sent_to_sign_in_elsewhere
AssertionError: 401 != 403
FAIL: test_a_visitor_is_sent_to_sign_in_elsewhere
AssertionError: 401 != 403
... (2 more like these)
Ran 76 tests in ...s
FAILED (failures=6)
In config/tests/test_public.py, the module’s docstring ends:
config/tests/test_public.py
Chapter 48: DRF's views opt out of the middleware and
follow DRF's own default instead, IsAuthenticated, so a
DRF view is public only if it says AllowAny, and refuses
a visitor with a problem instead of a redirect: since
Chapter 50, 401 with WWW-Authenticate: Bearer.
and the check for DRF’s views becomes:
config/tests/test_public.py
if drf_view(view) is not None:
self.assertEqual(page.status_code, 401)
self.assertEqual(page['WWW-Authenticate'],
'Bearer realm="api"')
In api/tests/test_writes.py, the two access tests become:
uv run python manage.py test api config.tests.test_public
Output
Found 76 test(s).
Creating test database for alias 'default'...
...
Ran 76 tests in ...s
OK
Step 5: Scopes
The tests, at the end of test_tokens.py:
api/tests/test_tokens.py
class ScopeTests(Tokens):
"""Each action needs its scope."""
# The action, its scope, and the request; all dry runs.
ACTIONS = [
('list', 'read', 'get', ''),
('retrieve', 'read', 'get', '{id}/'),
('partial_update', 'write', 'patch', '{id}/'),
('publish', 'publish', 'post', '{id}/publish/'),
('destroy', 'delete', 'delete', '{id}/'),
]
def send(self, api, method, path):
"""Send one action as a dry run; return the answer."""
address = MINE + path.format(id=self.event.pk)
return getattr(api, method)(
f'{address}?dry_run=true', {'title': 'New'},
format='json', headers={'If-Match': '"v1"'})
def test_each_action_needs_its_scope(self):
for action, scope, method, path in self.ACTIONS:
with self.subTest(action):
_, without = self.token(
[s for s in ALL if s != scope])
page = self.send(without, method, path)
self.assertEqual(page.status_code, 403)
self.assertIn(f'the {scope} scope',
page.json()['detail'])
Token.objects.update(revoked_at=timezone.now())
_, only = self.token([scope])
page = self.send(only, method, path)
self.assertIn(page.status_code, (200, 204))
Token.objects.update(revoked_at=timezone.now())
def test_a_refusal_is_recorded_with_the_token(self):
token, api = self.token(['read'])
self.send(api, 'patch', '{id}/')
row = AuditEvent.objects.get(outcome='refused')
self.assertEqual(
(row.action, row.token, row.detail),
('edit_event', token, {'scope': 'write'}))
def test_a_token_never_exceeds_its_owner(self):
_, raj = self.token(ALL, user=self.raj)
self.assertEqual(raj.get(self.address).status_code,
404)
_, sam = self.token(ALL)
self.sam.groups.clear()
self.assertEqual(sam.get(MINE).status_code, 403)
class AuditTests(Tokens):
"""The audit trail names the token behind a change."""
def patch(self, api, title, version):
"""Change the title, as version; return the answer."""
return api.patch(self.address, {'title': title},
format='json',
headers={'If-Match': f'"v{version}"'})
def test_a_change_names_the_token(self):
token, api = self.token(['write'])
self.assertEqual(self.patch(api, 'Agent', 1)
.status_code, 200)
row = AuditEvent.objects.get(action='edit_event')
self.assertEqual((row.actor, row.token),
(self.sam, token))
def test_the_next_request_forgets_the_token(self):
_, api = self.token(['write'])
self.patch(api, 'By the agent', 1)
session = APIClient()
session.force_login(self.sam)
self.patch(session, 'By Sam', 2)
rows = AuditEvent.objects.filter(
action='edit_event').order_by('id')
self.assertIsNotNone(rows[0].token)
self.assertIsNone(rows[1].token)
test_each_action_needs_its_scope sends every action twice, as dry runs: once with a token holding every scope except the one it needs, which must be refused by name, and once with a token holding only that scope. test_a_token_never_exceeds_its_owner uses Raj’s full token on Sam’s draft, and Sam’s after he leaves the Organizers group.
Terminal
uv run python manage.py test api.tests.test_tokens
Output
Found 17 test(s).
Creating test database for alias 'default'...
ERROR: test_a_refusal_is_recorded_with_the_token
audit.models.AuditEvent.DoesNotExist: AuditEvent matching
query does not exist.
FAIL: test_each_action_needs_its_scope [destroy]
AssertionError: 200 != 403
FAIL: test_each_action_needs_its_scope [list]
AssertionError: 200 != 403
... (3 more like these)
Ran 17 tests in ...s
FAILED (failures=5, errors=1)
The two audit tests already pass: Step 4’s class sets the context variable, and the middleware clears it. Create api/permissions.py:
api/permissions.py
"""What a program may do with its token (Chapter 50)."""
from rest_framework.permissions import BasePermission
from audit.models import AuditEvent, record
from .models import PersonalAccessToken
Scope = PersonalAccessToken.Scope
Action = AuditEvent.Action
# The scope each of the viewset's actions needs, and what a
# refusal is recorded as. A list or a read records nothing.
NEEDS = {
'list': (Scope.READ, None),
'retrieve': (Scope.READ, None),
'create': (Scope.WRITE, Action.CREATE_EVENT),
'partial_update': (Scope.WRITE, Action.EDIT_EVENT),
'publish': (Scope.PUBLISH, Action.PUBLISH_EVENT),
'cancel': (Scope.PUBLISH, Action.CANCEL_EVENT),
'destroy': (Scope.DELETE, Action.DELETE_EVENT),
}
class TokenScope(BasePermission):
"""A token must carry the scope its action needs.
A session, the site's own pages calling the API, has
every scope. Either way the view still asks the event
whether this member may change it, so a token never
does more than its owner may do now.
"""
def has_permission(self, request, view):
"""Return whether the request's token allows this."""
token = request.auth
if not isinstance(token, PersonalAccessToken):
return True
# A method the viewset does not answer, such as PUT,
# has no action; it needs read, then gets 405.
needed, action = NEEDS.get(view.action,
(Scope.READ, None))
if token.allows(needed):
return True
self.message = (f'This token does not have the '
f'{needed} scope.')
if action is not None:
record(request.user, action,
outcome=AuditEvent.Outcome.REFUSED,
scope=needed.value)
return False
request.auth is the second thing authenticate() returned: the token, or None for a session. A refusal is recorded as the attempted action, with the scope it lacked, and names the token through the same context variable.
In api/views.py, the permissions import becomes:
api/views.py
from rest_framework.permissions import (
AllowAny, IsAuthenticated,
)
add, above from .problems import (:
api/views.py
from .permissions import TokenScope
and the viewset’s first lines become:
api/views.py
serializer_class = MyEventSerializer
# Chapter 50: signed in, by session or token, and a
# token must carry the scope of the action it is used for.
permission_classes = [IsAuthenticated, TokenScope]
http_method_names = ['get', 'head', 'post', 'patch',
'delete']
Terminal
uv run python manage.py test api.tests.test_tokens
Output
Found 17 test(s).
Creating test database for alias 'default'...
...
Ran 17 tests in ...s
OK
Common Error: permission_classes replaces the default
Setting permission_classes on a view replaces DEFAULT_PERMISSION_CLASSES; it does not add to it. Writing [TokenScope] alone would let a visitor through, because TokenScope allows anything that is not a token. That is why the list starts with IsAuthenticated.
Step 6: Out of logs and error reports
Two tests prove the rule of Figure 50.2 that matters most when something goes wrong. Add them to the end of test_tokens.py:
api/tests/test_tokens.py
class SecrecyTests(Tokens):
"""A token never reaches logs or error reports."""
def test_logs_never_hold_the_token(self):
text = Token.issue(self.sam, 'agent', ALL)[1]
with self.assertLogs('django.request') as logs:
bearer(BAD).get(MINE)
APIClient().get(f'{MINE}?token={text}')
self.assertEqual(len(logs.output), 2)
for secret in (BAD, text):
self.assertNotIn(secret, '\n'.join(logs.output))
def test_error_reports_hide_the_header_only(self):
request = RequestFactory().get(
'/api/v1/my/events/?token=SECRET',
headers={'Authorization': 'Bearer SECRET'})
meta = SafeExceptionReporterFilter(
).get_safe_request_meta(request)
self.assertNotIn('SECRET', meta['HTTP_AUTHORIZATION'])
self.assertIn('SECRET', meta['QUERY_STRING'])
The first sends a wrong token in the header and a real one in the address, and reads every line Django logged: neither secret is there, because Django logs the path, not the headers or the query string. The second shows why the address is refused at all: Django’s error report hides the Authorization header and prints the query string as it came.
Terminal
uv run python manage.py test api.tests.test_tokens
Output
Found 19 test(s).
Creating test database for alias 'default'...
...
Ran 19 tests in ...s
OK
uv run python manage.py test api.tests.test_tokens.PageTests
Output
Found 6 test(s).
Creating test database for alias 'default'...
ERROR: test_a_new_token_is_shown_once
django.urls.exceptions.NoReverseMatch: Reverse for 'tokens'
not found. 'tokens' is not a valid view function or
pattern name.
ERROR: test_members_get_403_recorded
django.urls.exceptions.NoReverseMatch: Reverse for 'tokens'
not found. 'tokens' is not a valid view function or
pattern name.
ERROR: test_revoking_asks_the_password_and_only_mine
django.urls.exceptions.NoReverseMatch: Reverse for 'tokens'
not found. 'tokens' is not a valid view function or
pattern name.
... (3 more like these)
Ran 6 tests in ...s
FAILED (errors=6)
Create api/forms.py:
api/forms.py
"""The form for a new API token (Chapter 50)."""
from django import forms
from .models import DAYS, PersonalAccessToken
class TokenForm(forms.Form):
"""Name a token, choose its scopes and how long it lasts."""
name = forms.CharField(
max_length=60,
help_text='What uses it, such as "nightly import".')
scopes = forms.MultipleChoiceField(
choices=PersonalAccessToken.Scope.choices,
widget=forms.CheckboxSelectMultiple,
initial=[PersonalAccessToken.Scope.READ],
help_text='Give it only what the program needs.')
days = forms.TypedChoiceField(
label='Expires after', coerce=int, initial=90,
choices=[(d, f'{d} days') for d in DAYS])
and api/pages.py, kept apart from api/views.py, which holds the API itself:
api/pages.py
"""The API tokens page, for organizers (Chapter 50)."""
from functools import wraps
from allauth.account.decorators import (
reauthentication_required,
)
from django.contrib import messages
from django.core.exceptions import ValidationError
from django.shortcuts import get_object_or_404, redirect, render
from django.views.decorators.cache import never_cache
from django.views.decorators.http import (
require_http_methods, require_POST,
)
from audit.models import AuditEvent
from events.views import deny
from .forms import TokenForm
from .models import ORGANIZER, PersonalAccessToken
def organizers_only(view):
"""Allow only organizers; others get 403, recorded."""
@wraps(view)
def wrapper(request, *args, **kwargs):
if not request.user.has_perms(ORGANIZER):
deny(request, AuditEvent.Action.MANAGE_TOKENS)
return view(request, *args, **kwargs)
return wrapper
@require_http_methods(['GET', 'POST'])
@organizers_only
@reauthentication_required
@never_cache
def tokens(request):
"""List the member's tokens; make one, shown only once.
The new token's text is in this response only: it is
not stored, and never_cache keeps it out of caches.
"""
form = TokenForm(request.POST or None)
new = None
if form.is_valid():
try:
token, new = PersonalAccessToken.issue(
request.user, **form.cleaned_data)
except ValidationError as error:
form.add_error(None, error)
else:
form = TokenForm()
return render(request, 'api/tokens.html', {
'form': form, 'new': new,
'tokens': request.user.tokens.all(),
})
@require_POST
@organizers_only
@reauthentication_required
def revoke_token(request, token_id):
"""Revoke one of the member's own tokens.
The password is asked again, as for making one: a
laptop left signed in must not be enough to cut off
another program. allauth keeps the POST and sends it
on once the password is given.
"""
token = get_object_or_404(request.user.tokens,
pk=token_id)
token.revoke(request.user)
messages.success(request, f'Token {token.name} revoked.')
return redirect('tokens')
The new token is rendered in the answer to the POST, not stored and shown after a redirect: storing it, even for a moment in the session, would put the secret in the database. never_cache keeps that answer out of the browser’s cache. revoke_token asks for the password again as well. A form that posts to a view behind reauthentication_required is not lost: allauth keeps the POST, asks for the password, then sends the POST on.
Create api/templates/api/tokens.html:
api/templates/api/tokens.html
{% extends "base.html" %}
{% block title %}API tokens | Otahque{% endblock %}
{% block content %}
<h1>API tokens</h1>
<p>A token lets a program, such as a script or an AI
agent, use the API for you, without your password. It
can do only what its scopes allow, and never more than
you may do yourself.</p>
{% if new %}
<section class="token-card token-new" role="status"
aria-labelledby="new-heading">
<h2 id="new-heading">Copy your new token now</h2>
<p>It is shown only this once. Keep it where your
program reads it, never in code or an address.</p>
<p class="copy-field">
<code id="new-token">{{ new }}</code>
<button type="button" class="btn btn-primary btn-sm
needs-js" data-copy="new-token"
data-copied="Token copied.">Copy token</button>
</p>
</section>
{% endif %}
<div class="token-layout">
<section class="token-card" aria-labelledby="create">
<h2 id="create">Create a token</h2>
<form method="post" class="space-y-4">
{% csrf_token %}
{% include "includes/error_summary.html" %}
<div class="form-grid">{{ form }}</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary">
Create token</button>
</div>
</form>
</section>
<section aria-labelledby="yours">
<h2 id="yours" class="list-heading">Your tokens</h2>
<ul class="token-list">
{% for token in tokens %}
<li class="token-card">
<p class="token-head">
<strong>{{ token.name }}</strong>
{% if token.revoked_at %}
<span class="badge badge-outline">
Revoked</span>
{% elif token.is_active %}
<span class="badge badge-success">
Active</span>
{% else %}
<span class="badge badge-outline">
Expired</span>
{% endif %}
</p>
<p><code>{{ token.shown }}</code></p>
<p class="scope-badges">
<span class="sr-only">Scopes:</span>
{% for scope in token.scopes %}
<span class="badge badge-ghost">
{{ scope }}</span>
{% endfor %}
</p>
<dl class="facts text-sm">
<dt>Last used</dt>
<dd>
{% if token.last_used_at %}
{{ token.last_used_at|date:"j M Y, H:i" }}
{% else %}Never{% endif %}</dd>
<dt>Expires</dt>
<dd>{{ token.expires_at|date:"j M Y" }}</dd>
</dl>
{% if token.is_active %}
<form method="post"
action="{% url 'revoke_token' token.pk %}">
{% csrf_token %}
<button type="submit"
class="btn btn-outline btn-error btn-sm">
Revoke {{ token.name }}</button>
</form>
{% endif %}
</li>
{% empty %}
<li class="token-card">You have no tokens yet.</li>
{% endfor %}
</ul>
</section>
</div>
{% endblock %}
In config/urls.py, the API import becomes:
config/urls.py
from api import pages as api_pages
from api import views as api_views
and the two addresses follow the developers page:
config/urls.py
path('developers/', api_views.developers,
name='developers'),
# Chapter 50: tokens that let programs act for you.
path('accounts/tokens/', api_pages.tokens, name='tokens'),
path('accounts/tokens/<int:token_id>/revoke/',
api_pages.revoke_token, name='revoke_token'),
On the profile page, accounts/templates/accounts/profile.html, the Account security list gains a link for organizers:
accounts/templates/accounts/profile.html
<li><a href="{% url 'socialaccount_connections' %}">
Connected accounts</a></li>
{# Chapter 50: tokens for programs, for organizers. #}
{% if perms.events.add_event %}
<li><a href="{% url 'tokens' %}">API tokens</a></li>
{% endif %}
and the developers page, api/templates/api/developers.html, tells programs where to start:
api/templates/api/developers.html
<li>Add <code>?dry_run=true</code> to see what a
change would do, saving nothing.</li>
<li>From a program, send a token from your
<a href="{% url 'tokens' %}">API tokens</a> page as
<code>Authorization: Bearer otq_...</code>, never
in the address.</li>
</ul>
The UI increment. The Copy button from Chapter 49 announced “API address copied.” whatever it copied. In static/otahque/site.js, its comment becomes:
static/otahque/site.js
// Chapter 49: copy an address, and say so in the live
// region, which screen readers announce. One listener on
// the page also serves buttons htmx swaps in later.
// Chapter 50: any button may say what it copied, with
// data-copied, such as a new API token.
The shared improvement is in the form template every page uses. A group of checkboxes, such as the scopes, had a <label> pointing at no single field, so a screen reader announced each box without its question. templates/forms/field.html becomes:
templates/forms/field.html
{# Chapter 50: a group of checkboxes or radio buttons is #}
{# a fieldset, its question the legend, so a screen #}
{# reader names the group (WCAG 1.3.1). #}
{% if field.use_fieldset %}
<fieldset class="fieldset">
<legend class="fieldset-legend">{{ field.label }}</legend>
{% if field.help_text %}
<p class="label whitespace-normal"
id="{{ field.auto_id }}_helptext">
{{ field.help_text }}</p>
{% endif %}
{{ field.errors }}
<div class="choice-list">{{ field }}</div>
</fieldset>
{% else %}
<div class="fieldset">
<label class="fieldset-legend"
for="{{ field.id_for_label }}">
{{ field.label }}</label>
{% if field.help_text %}
<p class="label whitespace-normal"
id="{{ field.auto_id }}_helptext">
{{ field.help_text }}</p>
{% endif %}
{{ field.errors }}
{{ field }}
</div>
{% endif %}
field.use_fieldset is Django’s own flag, true for widgets such as CheckboxSelectMultiple and RadioSelect. The registration questions of Chapter 38 and the event list’s filters get the same fieldset. In static/otahque/source.css, above .form-actions:
static/otahque/source.css
/* Chapter 50: a group of checkboxes or radio buttons,
each choice a row with room to tap (form template). */
.choice-list > div {
display: grid;
gap: 0.5rem;
}
.choice-list label {
padding: 0.5rem 0.75rem;
border: 1px solid var(--color-base-300);
border-radius: var(--radius-field);
background-color: var(--color-base-100);
}
.choice-list label:has(:checked) {
border-color: var(--color-primary);
}
/* Chapter 50: API tokens; the form beside the list from
64rem, and a new token in a card of its own. */
.token-layout {
display: grid;
gap: 1.5rem;
align-items: start;
}
@media (width >= 64rem) {
.token-layout {
grid-template-columns: minmax(0, 2fr) minmax(0, 3fr);
}
}
.token-list {
display: grid;
gap: 0.75rem;
margin-top: 0.75rem;
}
.token-card {
display: grid;
gap: 0.5rem;
padding: 1.25rem;
border: 1px solid var(--color-base-300);
border-radius: var(--radius-box);
background-color: var(--color-base-100);
}
.token-card h2 {
font-size: 1.25rem;
font-weight: 700;
}
.token-new {
margin-bottom: 1.5rem;
border-left: 6px solid var(--color-success);
}
.token-head,
.scope-badges {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.5rem;
}
.copy-field {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.5rem;
}
.copy-field code {
padding: 0.25rem 0.5rem;
border-radius: var(--radius-field);
background-color: var(--color-base-200);
overflow-wrap: anywhere;
}
Terminal
npm run build
uv run python manage.py test api.tests.test_tokens.PageTests
Output
Found 6 test(s).
Creating test database for alias 'default'...
...
Ran 6 tests in ...s
OK
Step 8: Tokens in the OpenAPI file
drf-spectacular reads each view’s authentication classes to say how an operation is called, and it does not know Otahque’s. Create api/schema.py:
api/schema.py
"""How the OpenAPI file describes tokens (Chapter 50)."""
from drf_spectacular.extensions import (
OpenApiAuthenticationExtension,
)
class BearerScheme(OpenApiAuthenticationExtension):
"""Describe BearerAuthentication as HTTP bearer auth."""
target_class = 'api.authentication.BearerAuthentication'
name = 'token'
def get_security_definition(self, auto_schema):
"""Return the security scheme the file lists."""
return {
'type': 'http', 'scheme': 'bearer',
'description': 'A personal access token, otq_..., '
'from Account, API tokens.',
}
An extension is found only if its module is imported, so api/apps.py becomes:
api/apps.py
"""Configuration Django reads to load the api app."""
from django.apps import AppConfig
class ApiConfig(AppConfig):
"""Otahque's API for other programs (Chapter 47)."""
name = 'api'
def ready(self):
"""Load how the OpenAPI file describes tokens."""
from . import schema # noqa: F401
The organizer’s operations can now answer 401, which the file should say. In api/views.py, add above IF_MATCH:
api/views.py
# Chapter 50: missing or bad credentials.
NO_TOKEN = OpenApiResponse(
ProblemSerializer,
'Not signed in: send Authorization: Bearer otq_...')
and add 401: NO_TOKEN to each of the seven operations, before its 403. The decorator becomes:
api/views.py
@extend_schema_view(
list=extend_schema(
operation_id='listMyEvents',
summary='List the events you organize, drafts too.',
responses={200: inline_serializer('MyEventList', {
'results': MyEventSerializer(many=True)}),
401: NO_TOKEN, 403: PROBLEM}),
create=extend_schema(
operation_id='createDraft',
summary='Create a draft event that you organize.',
request=EventWriteSerializer, parameters=[DRY_RUN],
responses={201: MyEventSerializer, 401: NO_TOKEN,
403: PROBLEM, 422: INVALID}),
retrieve=extend_schema(
operation_id='getMyEvent',
summary='Read one of your events; its ETag is its '
'version.',
responses={200: MyEventSerializer, 401: NO_TOKEN,
403: PROBLEM, 404: PROBLEM}),
partial_update=extend_schema(
operation_id='changeMyEvent',
summary='Change some fields of one of your events.',
description='Send the ETag you read in If-Match. A '
'new timezone needs starts_at and ends_at '
'too. A higher capacity gives places to '
'waiting members; a new time or place '
'emails members holding places.',
request=EventWriteSerializer,
parameters=[DRY_RUN, IF_MATCH],
responses={200: MyEventSerializer, 401: NO_TOKEN,
403: PROBLEM, 404: PROBLEM, 412: PROBLEM,
422: INVALID, 428: PROBLEM}),
destroy=extend_schema(
operation_id='deleteDraft',
summary='Delete one of your drafts.',
parameters=[DRY_RUN],
responses={204: None, 401: NO_TOKEN,
403: PROBLEM, 404: PROBLEM,
422: INVALID}),
publish=extend_schema(
operation_id='publishMyEvent',
summary='Publish one of your drafts, if it is ready.',
request=None, parameters=[DRY_RUN],
responses={200: MyEventSerializer, 401: NO_TOKEN,
403: PROBLEM, 404: PROBLEM, 422: INVALID}),
cancel=extend_schema(
operation_id='cancelMyEvent',
summary='Cancel one of your published events.',
description='Every member holding a place is '
'emailed. Try it with dry_run first.',
request=None, parameters=[DRY_RUN],
responses={200: MyEventSerializer, 401: NO_TOKEN,
403: PROBLEM, 404: PROBLEM, 422: INVALID}),
)
Chapter 49’s drift test notices at once:
Terminal
uv run python manage.py test api.tests.test_openapi
Output
Found 7 test(s).
Creating test database for alias 'default'...
FAIL: test_the_file_is_what_the_code_makes
AssertionError: b'ope[496 chars] - cookieAuth: []\n -
{}\n respons[20536 chars]v1\n' != b'ope[496 chars]
- token: []\n - cookieAuth: []\n [22421
chars]v1\n' : Run: uv run python manage.py spectacular
--file docs/api/openapi.yaml
Ran 7 tests in ...s
FAILED (failures=1)
Make the file from the code, read its diff (each operation now lists token beside cookieAuth, and the organizer’s operations list 401), and run the test again:
Terminal
uv run python manage.py spectacular --file docs/api/openapi.yaml
uv run python manage.py test api.tests.test_openapi
Output
Found 7 test(s).
Creating test database for alias 'default'...
...
Ran 7 tests in ...s
OK
Step 9: The records
The permission matrix gains its API rows, proved by one more test class at the end of test_tokens.py:
api/tests/test_tokens.py
class MatrixTests(TestCase):
"""The permission matrix's API rows: Sam's draft."""
# Who asks: list, read the draft as its organizer,
# change it (a dry run). The detail is the organizer's
# view, so an administrator gets 403, as on the edit page.
ROWS = {
'visitor': (401, 401, 401),
'member': (403, 404, 404),
'other organizer': (200, 404, 404),
'administrator': (200, 403, 403),
'superuser': (200, 403, 403),
'organizer': (200, 200, 200),
'organizer, read token': (200, 200, 403),
'organizer, full token': (200, 200, 200),
}
@classmethod
def setUpTestData(cls):
cls.sam = in_group('sam@example.org', 'Organizers')
cls.event = ready(title='Clinic')
cls.event.add_organizer(cls.sam)
cls.people = {
'member': verified('sai@example.org'),
'other organizer': in_group('raj@example.org',
'Organizers'),
'administrator': in_group('ann@example.org',
'Administrators'),
'superuser': get_user_model().objects
.create_superuser('root@example.org', 'x' * 20,
display_name='Root'),
'organizer': cls.sam,
}
def client_for(self, who):
"""Return an API client acting as who."""
if who.startswith('organizer, '):
scopes = ['read'] if 'read' in who else ALL
return bearer(Token.issue(self.sam, who, scopes)[1])
api = APIClient()
if who in self.people:
api.force_login(self.people[who])
return api
def test_each_row(self):
address = f'{MINE}{self.event.pk}/'
for who, expected in self.ROWS.items():
api = self.client_for(who)
got = (
api.get(MINE).status_code,
api.get(address).status_code,
api.patch(f'{address}?dry_run=true',
{'title': 'New'}, format='json',
headers={'If-Match': '"v1"'})
.status_code,
)
with self.subTest(who):
self.assertEqual(got, expected)
Terminal
uv run python manage.py test api.tests.test_tokens.MatrixTests
Output
Found 1 test(s).
Creating test database for alias 'default'...
...
Ran 1 test in ...s
OK
The administrator’s 403 on reading Sam’s draft may surprise: /api/v1/my/events/{id}/ is the organizer’s view of an event, so it answers as the edit page does, where the administrator also gets 403. The public event page is still theirs to read.
In docs/design/permissions.md, the “Planned rows” section’s Chapter 50 line is replaced by a section of its own, above it:
docs/design/permissions.md
## The API (Chapter 50)
The organizer's own events at /api/v1/my/events/ follow
the rules above, by session or by a personal access
token. A token acts for its owner, never with more than
the owner may do now, and only within its scopes: read
(list, read), write (create, change), publish (publish,
cancel), delete (delete a draft). A session has all four.
| Person | List | Read | Change |
|-----------------------|------|------|--------|
| Visitor | 401 | 401 | 401 |
| Member | 403 | 404 | 404 |
| Other organizer | ok | 404 | 404 |
| Administrator | ok | 403 | 403 |
| Superuser | ok | 403 | 403 |
| Organizer | ok | ok | ok |
| Organizer, read token | ok | ok | 403 |
Read is the organizer's view of Sam's draft, so it
answers as the edit page does. A list for someone who
organizes nothing is empty. Proved by MatrixTests in
api/tests/test_tokens.py.
- Missing or bad credentials: 401 with
WWW-Authenticate: Bearer. A token in the address: 400,
never checked.
- Only organizers make tokens, on the API tokens page,
after giving the password again; at most five active,
each expiring in 7, 30, or 90 days. Revoking one asks
for the password again too.
- Making, revoking, and every change made with a token
are recorded; the record names the token.
In docs/api/contract.md, the error table begins:
docs/api/contract.md
| Status | When |
|---|---|
| 400 | A token in the address; revoke it |
| 401 | No credentials, or a bad token |
| 403 | Signed in but not allowed, or a missing scope |
and the organizer’s section gains, after its first paragraph:
docs/api/contract.md
A program sends a personal access token, made on the API
tokens page, in a header (Chapter 50):
Authorization: Bearer otq_...
Never in the address: `?token=` and `?access_token=` are
refused with 400. Missing or bad credentials get 401 with
`WWW-Authenticate: Bearer`. A token carries scopes, and
each action needs one: `read` to list and read, `write`
to create and change, `publish` to publish and cancel,
`delete` to delete a draft; without it, 403. A token
never does more than its owner may do now, and every
change it makes is recorded with its name.
Record the decision as docs/adr/ADR-008-api-tokens.md:
docs/adr/ADR-008-api-tokens.md
# ADR-008: Personal access tokens for programs
## Status
Proposed, December 2026 (Chapter 50). The choices follow
the user's decisions of 30 November 2026 (D50.1, D50.2,
N50.5-N50.8); this record is not yet reviewed or accepted.
## Context
Since Chapter 48 an organizer's events can be changed
through /api/v1/my/events/, with the site's session only.
A script or an AI agent cannot hold a session or a CSRF
token, and must never hold a password. Its credential
must be easy to revoke, limited to what the program
needs, kept out of logs and addresses, and traceable in
the audit trail.
## Options
- A: Otahque's own tokens: otq_, an id, and a secret;
the secret stored as SHA-256; scopes, expiry,
revocation, and last use.
- B: DRF's TokenAuthentication: one plain-text key per
member in the database, no expiry, no scopes.
- C: django-rest-knox 6.0.0: hashed, expiring tokens
that support Django 6.1, released ten days earlier,
without scopes.
- D: an OAuth 2 server: a protocol for third-party
applications, more than one community needs.
## Decision
A, in the api app.
- Only organizers make or revoke tokens, on the API
tokens page, after giving the password again; at most
five active; each expires in 7, 30, or 90 days (90 by
default).
- Scopes: read (list, read), write (create, change),
publish (publish, cancel), delete (delete a draft). A
session has all four. A token never does more than its
owner may do now: each request still asks the event.
- BearerAuthentication runs first, so missing or bad
credentials get 401 with WWW-Authenticate: Bearer; a
signed-in member who may not act gets 403.
- A token in the address (token or access_token) is
refused with 400 and never checked: error reports and
server logs keep addresses, not the header.
- Each audit record names the token used, through a
context variable that record() reads; no model method
changes.
## Consequences
- A leaked token is found by its otq_ prefix, revoked on
the page, and traced through the audit trail.
- The secret is shown once; a lost token is replaced,
never recovered.
- Programs other than the organizer's own (partners
acting for many members) are not served. Revisit if
that need appears: OAuth 2 then, option D.
- Throttling per token: Chapter 51.
Step 10: Make a token in a browser
Run the server:
Terminal
uv run python manage.py runserver
Sign in as Sam, open Your profile, and follow API tokens. Otahque asks for the password again. Name a token “nightly import”, tick Read your events and Create drafts and change events, choose 30 days, and press Create token. Copy the token now: it will not be shown again. Figure 50.3 shows the page on a phone and on a wide screen.
Figure 50.3 — The API tokens page: a new token, shown once.
Press Revoke on any test token you made; if more than five minutes have passed, Otahque asks for the password first. Its card then says Revoked, and it will never work again.
Step 11: Sam’s script
Create examples/my_events.py, a script that uses only Python’s standard library:
examples/my_events.py
"""List my Otahque events from a script, with a token.
Chapter 50. Run it with two environment variables set:
OTAHQUE_URL, such as http://127.0.0.1:8000, and
OTAHQUE_TOKEN, a token from Account, API tokens. The token
is read from the environment, never written in this file,
and sent only in the Authorization header.
"""
import json
import os
import sys
import urllib.error
import urllib.request
def get(path):
"""Return the JSON at path, sent with the token."""
request = urllib.request.Request(
os.environ['OTAHQUE_URL'] + path,
headers={
'Authorization':
'Bearer ' + os.environ['OTAHQUE_TOKEN'],
'Accept': 'application/json',
})
with urllib.request.urlopen(request, timeout=10) as answer:
return json.load(answer)
def main():
"""Print each of my events: id, status, and title."""
try:
events = get('/api/v1/my/events/')['results']
except urllib.error.HTTPError as error:
problem = json.load(error)
print(error.code, problem['detail'], file=sys.stderr)
return 1
for event in events:
print(f"{event['id']:>4} {event['status']:<10}"
f"{event['title']}")
return 0
if __name__ == '__main__':
sys.exit(main())
The token comes from the environment, never from the file, so the script can be committed and the token cannot. With the server still running, in a second terminal, set the two values and run it.
PowerShell:
Windows PowerShell
$env:OTAHQUE_URL = 'http://127.0.0.1:8000'
$env:OTAHQUE_TOKEN = 'otq_...'
uv run python examples/my_events.py
macOS, Linux, or WSL:
Git Bash, macOS, or Linux
export OTAHQUE_URL='http://127.0.0.1:8000'
export OTAHQUE_TOKEN='otq_...'
uv run python examples/my_events.py
Output
1 published Python meetup
6 published Online Django clinic
Your list holds your own events. With a wrong token, the script prints the problem’s detail and exits with 1:
Output
401 The token is not valid.
Common Error: the token in a URL, a commit, or a chat
curl "http://127.0.0.1:8000/api/v1/my/events/?token=otq_..." gets 400, and the token is now in the server’s log; revoke it. A token pasted into the script, or into a .env that Git tracks, ends up in the repository’s history for good. Keep it in an environment variable or a password manager, and give each program its own.
Step 12: Optional lab: sign in with GitHub
This lab changes nothing in the project, and the book’s checks did not run it. Chapter 27 configured allauth for Google and GitHub, used only when their client IDs are in .env. To try GitHub sign-in end to end, register a test OAuth app in your GitHub account’s developer settings, with the callback address http://127.0.0.1:8000/accounts/github/login/callback/, put its values in .env as DJANGO_GITHUB_CLIENT_ID and DJANGO_GITHUB_SECRET, restart the server, and choose GitHub on the sign-in page. A first sign-in still shows the sign-up form, so every member has a display name. Delete the test app when you have finished. Signing in with GitHub gives a session, not a token: a script still needs a token made on the API tokens page, and the page still asks you to confirm who you are first, by the second factor if you have no password.
Step 13: The checks, and the commit
Stop the server, then:
Terminal
uv run python check.py
Output
== python manage.py check
System check identified no issues (0 silenced).
== python manage.py makemigrations --check --dry-run
No changes detected
== python manage.py test --parallel
Found 711 test(s).
System check identified no issues (0 silenced).
Ran 711 tests in ...s
OK
== all checks passed
Terminal
git add .
git status --short
git commit -m "Give programs tokens with scopes"
Output
M accounts/templates/accounts/profile.html
M api/apps.py
A api/authentication.py
A api/forms.py
A api/migrations/0001_initial.py
M api/models.py
A api/pages.py
A api/permissions.py
A api/schema.py
M api/templates/api/developers.html
A api/templates/api/tokens.html
A api/tests/test_tokens.py
M api/tests/test_writes.py
M api/views.py
A audit/middleware.py
A audit/migrations/0007_tokens.py
M audit/models.py
M config/settings.py
M config/tests/test_public.py
M config/urls.py
A docs/adr/ADR-008-api-tokens.md
M docs/api/contract.md
M docs/api/openapi.yaml
M docs/design/permissions.md
M events/templates/events/manage.html
A examples/my_events.py
M static/otahque/site.css
M static/otahque/site.js
M static/otahque/source.css
M templates/forms/field.html
[main 1a2b3c4] Give programs tokens with scopes
30 files changed, 1413 insertions(+), 27 deletions(-)
create mode 100644 api/authentication.py
create mode 100644 api/forms.py
create mode 100644 api/migrations/0001_initial.py
create mode 100644 api/pages.py
create mode 100644 api/permissions.py
create mode 100644 api/schema.py
create mode 100644 api/templates/api/tokens.html
create mode 100644 api/tests/test_tokens.py
create mode 100644 audit/middleware.py
create mode 100644 audit/migrations/0007_tokens.py
create mode 100644 docs/adr/ADR-008-api-tokens.md
create mode 100644 examples/my_events.py
If something goes wrong
Table 50.3 — Recovery for Chapter 50
What you see
Likely cause
What to do
403, not 401, with no WWW-Authenticate
BearerAuthentication is not first
Put it first in DEFAULT_AUTHENTICATION_CLASSES
401 for a token that works elsewhere
Expired, revoked, or the owner is inactive
Check the tokens page; make a new token
A visitor reaches my/events
permission_classes lost IsAuthenticated
List IsAuthenticated before TokenScope
400 "never in the address"
token= or access_token= in the URL
Send Authorization: Bearer; revoke that token
Audit rows name a token for page edits
CredentialMiddleware missing
Add it to MIDDLEWARE
The tokens page loops to the password
The password was wrong, or five minutes passed
Give it again; allauth's limit is five minutes
spectacular warns it could not resolve the authenticator
Work through Table 50.4 from the folder that holds manage.py, with Otahque on PostgreSQL.
Table 50.4 — Verification checklist for Chapter 50
Check
Command or action
Expected result
Starting point
test --parallel
Found 685 test(s); OK
Who is calling, before
who.py in the shell
Three 403s, none asking for a scheme
The model
test api.tests.test_tokens
ImportError first; then 4 tests OK
Bearer first
the same; who.py again
12 tests OK; 401 asking for Bearer
Changed on purpose
test api config.tests.test_public
Red: 403 expected; then OK
Scopes
test api.tests.test_tokens
17 tests OK
Out of logs
test api.tests.test_tokens
19 tests OK
The page
test ...test_tokens.PageTests
Errors first; then 6 tests OK
The OpenAPI file
test api.tests.test_openapi; spectacular --file
Red until the file is made; then 7 tests OK
The matrix
test ...test_tokens.MatrixTests
1 test OK
In a browser
/accounts/tokens/ at 390 and 1280 px
Shown once, copied, revoked
Sam's script
examples/my_events.py with the token
Your events listed; a wrong token: 401
All checks
uv run python check.py
== all checks passed; Ran 711 tests
Commit
git log --oneline -1
Give programs tokens with scopes
Not verified
The GitHub sign-in lab; macOS and Linux shells; a real secret scanner
Try the lab with your own test app
The commands were checked in Windows PowerShell 5.1 and Git Bash, from a copy of the Chapter 49 checkpoint with a reader’s data, against PostgreSQL 18; commands that write files ran once. In Microsoft Edge, at 390 and 1280 pixels, a Playwright script signed in as Sam (with the password check recorded as just given), followed API tokens from the profile, made a token at each width, pressed Copy token and read the clipboard back (it held the token shown, the button said Copied, and the live region said “Token copied.”), then revoked the phone’s token and found its card marked Revoked; there was no sideways scroll, and every control had a name. The script of Step 11 then ran in both shells with the token the browser made, against the development server.
Que. 1 A request to /api/v1/my/events/ carries no credentials. What does Otahque answer now, and why did it answer differently in Chapter 49?
Flip to check your answerFold answer back
Answer. 401 with WWW-Authenticate: Bearer realm="api". DRF answers 401 only when the first authentication class names a scheme; in Chapter 49 the only class was the session’s, which names none, so the answer was 403.
Que. 2 Why is a token’s secret stored as SHA-256 and not with Django’s password hasher?
Flip to check your answerFold answer back
Answer. A slow hasher protects secrets people choose, which can be guessed. A 32-character random secret cannot be guessed, so a fast hash is enough, and it keeps every API request cheap.
Que. 3 Sam’s token has the read scope only. What does a PATCH with it get, and what is recorded?
Flip to check your answerFold answer back
Answer. 403 saying the token does not have the write scope, and a refused edit_event audit record naming the token, with the scope it lacked.
Que. 4 Why is ?token= refused instead of read?
Flip to check your answerFold answer back
Answer. Addresses are copied into logs, history, and error reports, which mask the Authorization header but not the query string. A token there may already have leaked, so it is refused unchecked, and the answer says to revoke it.
Que. 5 How does record() know which token was used, without a new argument?
Flip to check your answerFold answer back
Answer. The authentication class sets a context variable for the request, record() reads it, and CredentialMiddleware clears it when the request ends.
Mini-Challenge
A token is for the API only. Write a test, in api/tests/test_token_pages.py, showing that a site page such as My events ignores Authorization: Bearer and still sends the visitor to sign in.
Hint:Token.issue() returns the token and its text; the test client’s get() accepts headers.
Model answer:
api/tests/test_token_pages.py
"""A token works on the API only (Chapter 50 challenge)."""
from django.test import TestCase
from django.urls import reverse
from api.models import PersonalAccessToken as Token
from config.helpers import in_group
class TokenOnPagesTests(TestCase):
"""The site's pages never read Authorization."""
def test_a_token_does_not_sign_in_on_a_page(self):
sam = in_group('sam@example.org', 'Organizers')
text = Token.issue(sam, 'agent', ['read'])[1]
manage = reverse('events:manage')
page = self.client.get(manage, headers={
'Authorization': f'Bearer {text}'})
self.assertRedirects(
page, f"{reverse('account_login')}?next={manage}",
fetch_redirect_response=False)
Terminal
uv run python manage.py test api.tests.test_token_pages
Output
Found 1 test(s).
Creating test database for alias 'default'...
...
Ran 1 test in ...s
OK
The pages use Django’s AuthenticationMiddleware, which reads only the session, so a token never signs anyone in to a page. The model answer was run and then removed; the chapter’s checkpoint does not include it.
What We Learned
Authentication asks who is calling; authorization asks whether they may. DRF asks them in that order, and the first authentication class decides between 401 and 403.
A personal access token is random, shown once, stored as a hash, compared in constant time, scoped, expiring, and revocable.
A Bearer header that fails is refused, never passed on to the session.
Scopes narrow a token; they never add a right. The event’s own methods still decide each request.
Tokens stay out of addresses: such requests are refused unchecked, because logs and error reports keep query strings.
A context variable lets record() name the token without changing any model method, and a middleware keeps it inside one request.
Making or revoking a token asks for the password again.
Key terms
Use Table 50.5 to explain this chapter’s ideas in your own words.
Table 50.5 — Key terms from Chapter 50
Term
Meaning
Authentication
Finding out who is asking.
Authorization
Deciding whether they may do this.
401 Unauthorized
Unknown caller; WWW-Authenticate says what to send.
403 Forbidden
Known caller, refused.
Personal access token
A member's credential for one program.
Bearer token
A token sent as Authorization: Bearer ...
Scope
The kind of action a token may be used for.
Hash
A one-way digest; SHA-256 here.
Constant-time comparison
hmac.compare_digest(): timing reveals nothing.
Context variable
A value that belongs to one request.
Re-authentication
Giving the password again before a sensitive page.
Readiness checkpoint: you are ready for Chapter 51 when uv run python check.py ends with “all checks passed” and 711 tests, the API tokens page makes and revokes a token, examples/my_events.py lists your events with it, and git log --oneline -1 shows this chapter’s commit.
Git Commit
Your Chapter 50 work was committed once, in Step 13, as “Give programs tokens with scopes”: the token model and its migration, the audit link and its migration, the authentication and permission classes, the middleware, the form, the page and its template, the schema module, the settings, views, addresses, and app configuration, the profile, developers, and My events templates, the form field template, the script and stylesheet with the compiled CSS, the OpenAPI file, the contract, the permission matrix, ADR-008, the example script, the new test module, and the two changed ones. If you kept the Mini-Challenge, commit it on its own:
Terminal
git add api/tests/test_token_pages.py
git commit -m "Check that pages ignore API tokens"
These five questions rehearse the chapter at interview level, from junior to lead. L1 to L3 check what you have just done. L4 and L5 look ahead, to a page script refused for CSRF and to the choice of not building OAuth. They are extension questions, not a gate to the next chapter. Proof files are run with uv run python manage.py shell -v 0 -c "exec(open('NAME').read())" and deleted afterwards.
L1 (Junior): Authentication or authorization: which gives 401, and which 403?
What the interviewer is testing: Can you tell the two questions apart, and map them to status codes?
Flip to check your answerFold answer back
Perfect answer: Authentication is working out who is calling; authorization is deciding whether that caller may do this. 401 is an authentication answer: no credentials, or bad ones, and the response names the scheme to use in WWW-Authenticate. 403 is an authorization answer: the caller is known and refused, and sending other credentials of the same person will not help. In Otahque, a visitor or a revoked token gets 401; Sam’s read-only token trying a PATCH, or Raj trying to change Sam’s published event, gets 403.
Table 50.6 — Who gets which answer
Caller
Status
Because
No credentials
401
Unknown; told to send Bearer
Revoked or expired token
401
Unknown from now on
Read token, PATCH
403
Known; lacks write
Raj, Sam's published event
403
Known; not its organizer
Behind the scenes:
Output
401 WWW-Authenticate: Bearer realm="api"
403 {"detail": "This token does not have
the write scope."}
Code proof: the permission matrix’s API rows:
Output
Found 1 test(s).
Creating test database for alias 'default'...
...
Ran 1 test in ...s
OK
Common mistakes:
Answering 401 for “not allowed”, which tells a client to retry with other credentials that will not help.
Sending 401 without WWW-Authenticate, which RFC 9110 requires.
Follow-up the interviewer might ask:
Why is a hidden draft 404, not 403? (Answering 403 would confirm the draft exists; Chapter 30 chose 404 so an id reveals nothing.)
L2 (Mid-Level): Predict what Raj’s token does to Sam’s events
What the interviewer is testing: Can you trace authentication, scopes, and object rules together?
Flip to check your answerFold answer back
Perfect answer: Raj’s token authenticates Raj: it is valid, so there is no 401. It carries read and write, so TokenScope lets a PATCH through. Then event_to_manage() asks the event, exactly as the edit page does: Sam’s draft is not visible to Raj, so it is 404; Sam’s published event is visible but Raj does not organize it, so it is 403. Both refusals are recorded as edit_event refused, by Raj, naming his token. Scopes only narrow what Raj may do; they cannot give him Sam’s events.
Figure 50.4 — Raj’s token against Sam’s events.
Behind the scenes:
Output
authenticate Raj, via raj-agent
TokenScope write: allowed
the event draft: 404, published: 403
audit edit_event refused, via raj-agent
Code proof: Raj’s token against a draft and a published event of Sam’s, made and rolled back:
l2_proof.py
"""Raj's token against Sam's events (Chapter 50, L2)."""
from datetime import timedelta
from django.contrib.auth.models import Group
from django.db import transaction
from django.test import Client
from django.utils import timezone
from accounts.models import User
from api.models import PersonalAccessToken as Token
from audit.models import AuditEvent
from events.models import Event
sam = User.objects.get(email='sam@example.org')
start = timezone.now() + timedelta(days=30)
with transaction.atomic():
raj = User.objects.create_user('raj.proof@example.org',
display_name='Raj')
raj.groups.add(Group.objects.get(name='Organizers'))
text = Token.issue(raj, 'raj-agent', ['read', 'write'])[1]
api = Client(HTTP_HOST='localhost',
HTTP_AUTHORIZATION=f'Bearer {text}')
for status in ('draft', 'published'):
event = Event.objects.create(
title=f'Sam {status}', starts_at=start,
ends_at=start + timedelta(hours=2),
timezone='Europe/London', location='Leeds',
capacity=10, status=status)
event.add_organizer(sam)
answer = api.patch(
f'/api/v1/my/events/{event.pk}/',
'{"title": "Raj was here"}',
content_type='application/json',
headers={'If-Match': '"v1"'})
print(f'{status:9} {answer.status_code}',
answer.json()['title'])
for row in AuditEvent.objects.filter(token__owner=raj):
print('recorded:', row.action, row.outcome,
'by', row.actor.display_name,
'via', row.token.name)
transaction.set_rollback(True)
Output
draft 404 Not Found
published 403 Forbidden
recorded: edit_event refused by Raj via raj-agent
recorded: edit_event refused by Raj via raj-agent
Common mistakes:
Checking only the scope, so any organizer’s write token changes any event.
Answering 403 for the draft, which confirms it exists.
Follow-up the interviewer might ask:
What changes if Raj becomes the event’s organizer? (Nothing in the token: the next request is allowed, because the rule is read each time.)
L3 (Senior): Defend storing tokens as a fast hash
What the interviewer is testing: Can you match a storage design to the threat, not to a habit?
Flip to check your answerFold answer back
Perfect answer: The threat is a copy of the database: a backup on the wrong disk, or a read-only leak. Stored as written, every token in it would work. So Otahque stores only a hash. Passwords need a slow hash because people choose them and an attacker can guess the likely ones; a 32-character random secret has about 190 bits, which no attacker can guess at any speed, so SHA-256 protects it fully and costs microseconds on each request, where a password hasher would cost a noticeable fraction of a second on every call. The row is found by the token’s public id and the hashes compared with hmac.compare_digest(), so neither the database query nor the comparison depends on the secret. The cost: a lost token cannot be recovered, only replaced, which is why it is shown once.
Figure 50.5 — Storing a token.
Behind the scenes:
Output
text otq_ + key (8) + _ + secret (32)
row key, sha256(secret), scopes, dates
check row by key; compare_digest(hashes)
Code proof: what the database keeps, made and rolled back:
l3_proof.py
"""What Otahque keeps of a token (Chapter 50, L3)."""
from django.db import transaction
from accounts.models import User
from api.models import PersonalAccessToken as Token
sam = User.objects.get(email='sam@example.org')
with transaction.atomic():
token, text = Token.issue(sam, 'proof', ['read'])
secret = text.rsplit('_', 1)[1]
row = Token.objects.filter(pk=token.pk).values().get()
print('shown once:', text[:4], len(text), 'characters')
print('kept:', len(row['secret_hash']), 'hex characters')
print('secret in the row:', secret in str(row))
print('found by its text:', Token.find(text) == token)
wrong = text[:-1] + ('a' if text[-1] != 'a' else 'b')
print('one character wrong:', Token.find(wrong))
transaction.set_rollback(True)
Output
shown once: otq_ 45 characters
kept: 64 hex characters
secret in the row: False
found by its text: True
one character wrong: None
Common mistakes:
Using a password hasher for random tokens, and paying for it on every request.
Looking the token up by its full text, so the database compares secrets.
Follow-up the interviewer might ask:
Would a short, six-digit code be safe with SHA-256? (No: a million codes can be hashed in moments; short secrets need a slow hash, rate limits, or both.)
L4 (Senior): A page’s script gets 403 from the API. Diagnose it
What the interviewer is testing: Can you tell a CSRF refusal from a permission one, and fix the right side?
Flip to check your answerFold answer back
Perfect answer: First read the problem’s detail. “CSRF Failed” means the caller was authenticated by its session cookie and sent no CSRF token, which SessionAuthentication requires for every write, because the browser sends the cookie even for requests another site starts. The fix is in the page’s script: read the csrftoken cookie, or the token Django rendered, and send it as X-CSRFToken, as htmx does in Otahque since Chapter 45. If instead the detail names a scope or says permission denied, CSRF is fine and the member may not do it. A program outside the browser should not use a session at all: with a token in Authorization, there is no cookie to abuse and no CSRF token to send.
Figure 50.6 — Diagnosing a session’s 403.
Behind the scenes:
Output
POST my/events/ (session, no token)
403 {"detail": "CSRF Failed: CSRF cookie
not set."}
send X-CSRFToken: <csrftoken cookie>
Code proof: Sam’s session, a dry-run create without and with the CSRF token:
l4_proof.py
"""A session call to the API, with and without CSRF (L4)."""
from django.test import Client
from accounts.models import User
ADDRESS = '/api/v1/my/events/?dry_run=true'
DRAFT = ('{"title": "Clinic", "location": "Leeds",'
' "starts_at": "2027-03-01T18:00:00Z",'
' "ends_at": "2027-03-01T20:00:00Z",'
' "timezone": "Europe/London", "capacity": 10}')
browser = Client(HTTP_HOST='localhost',
enforce_csrf_checks=True)
browser.force_login(User.objects.get(email='sam@example.org'))
answer = browser.post(ADDRESS, DRAFT,
content_type='application/json')
print('no CSRF token:', answer.status_code,
answer.json()['detail'])
browser.get('/accounts/profile/')
token = browser.cookies['csrftoken'].value
answer = browser.post(ADDRESS, DRAFT,
content_type='application/json',
headers={'X-CSRFToken': token})
print('with the token:', answer.status_code,
'dry_run', answer.json()['dry_run'])
Output
no CSRF token: 403 CSRF Failed: CSRF cookie not set.
with the token: 200 dry_run True
Common mistakes:
Marking the view csrf_exempt, which lets any site make a signed-in browser write.
Moving the page’s own calls to a token stored in the page, where any script on it can read it.
Follow-up the interviewer might ask:
Why does a Bearer token need no CSRF protection? (A browser never adds it on its own, so another site cannot make the browser send it.)
L5 (Lead): Why not build an OAuth 2 server?
What the interviewer is testing: Can you choose the smallest design that meets the need, and say when it stops being enough?
Flip to check your answerFold answer back
Perfect answer: OAuth 2 solves a different problem: an application written by someone else acting for many members, each of whom grants it access through a consent screen, with tokens that refresh and a registry of client applications. Otahque’s need is an organizer’s own scripts and agents acting for that organizer. Personal access tokens meet it with one model, one authentication class, and one permission class, all tested here, and the scopes, expiry, revocation, and audit trail an OAuth server would also need. Building OAuth now would add a protocol to secure and nobody to use it. ADR-008 records the choice and its trigger: if a partner asks to act for members who are not its own staff, we revisit, with an established library rather than our own server.
Figure 50.7 — Tokens now, OAuth when the need changes.
Behind the scenes:
Output
need now my own programs, for me
built PersonalAccessToken + scopes
not built OAuth 2 server (ADR-008)
revisit partners acting for members
Code proof: every token rule, in one test module:
Output
Found 26 test(s).
Creating test database for alias 'default'...
...
Ran 26 tests in ...s
OK
Common mistakes:
Building OAuth because large APIs have it, without a third-party client to serve.
Calling personal tokens “OAuth tokens”: they share the Bearer header, not the protocol.
Follow-up the interviewer might ask:
What would Chapter 51 add for tokens? (A limit on how often each token may call, so one runaway script cannot crowd out everyone else.)
Next: Chapter 51, filtering, pagination, throttling, and API documentation, lets programs ask for just the events they need, a page at a time, within limits, and gives them a page that documents every operation.