Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 39 ยท Testing and Deployment

Testing Authentication, Permissions and Throttling in DRF

Test Django REST Framework security rules: a permission matrix with subTest, token and session login flows, CSRF checks, object-level permissions and throttle limits with a controlled clock.

Security rules are the part of an API where a missing test hurts most. A forgotten permission check does not crash anything; it just quietly lets the wrong person in. Because those bugs are silent, the only reliable defence is a test that states each rule and fails when someone breaks it.

This lesson shows patterns for testing the topics of the earlier chapters: permission classes, object-level permissions, token authentication, session login with CSRF, and throttling. If you have not seen APITestCase yet, read Testing DRF APIs first.

Pattern 1: the permission matrix

Write the rules as a table: who (rows) may do what (columns), and loop over it. A table is easy to review, and adding a new role is one more row. unittest's subTest (or pytest.mark.parametrize) reports each failing cell separately.

Python A permission matrix with subTest

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Output:

TEXT
ran 3 | failures: 1 | errors: 0
FAILED: test_wrong_expectation_is_reported
   AssertionError: 403 != 200

The deliberate failure at the end shows what a broken rule looks like: the last line of the traceback names the two unequal values (403 != 200). In your own suite you would of course fix the code or the expectation instead of leaving it failing.

Two lessons hide in the matrix: a stranger gets 403 on a document that exists (the object permission refused it), and anonymous users also get 403 because the first authentication class (session) sends no WWW-Authenticate header. If your API uses token authentication first, the same request gives 401, which clients can tell apart from "logged in but not allowed".

Pattern 2: real login flows

force_authenticate skips the credential machinery on purpose, so you also need a few tests that go through the real login: obtain a token, send it, and check that wrong credentials fail. Test these once per scheme, not on every endpoint.

For session authentication add one more concern, CSRF. DRF enforces CSRF only for session-authenticated requests. APIClient disables the check by default to keep tests simple; construct it with enforce_csrf_checks=True to test the real behaviour.

Python Token login, session login and CSRF

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Output:

TEXT
no credentials                         401 {'detail': 'Authentication credentials were not provided.'}
login with a wrong password            400 {'non_field_errors': ['Unable to log in with provided credentials.']}
with the token                         200 {'user': 'mia', 'via': 'TokenAuthentication'}
with a forged token                    401 {'detail': 'Invalid token.'}
session login ok: True
session GET (safe method)              200 {'user': 'mia', 'via': 'SessionAuthentication'}
session POST without CSRF token        403 {'detail': 'CSRF Failed: CSRF cookie not set.'}

A POST with a session but no CSRF token is refused with 403 CSRF Failed, while the same request with a token header works without any CSRF cookie. That difference is the reason mobile and script clients prefer tokens and browsers rely on sessions.

For JWT, the pattern is identical: post credentials to the token endpoint, read the access value, and set HTTP_AUTHORIZATION="Bearer <access>". Add tests for an expired access token (create one with a negative lifetime) and for the refresh flow; see JWT authentication.

Pattern 3: testing throttles with a controlled clock

Throttle tests must not sleep. Two things make them reliable: clear the cache before each test (the counters live there) and replace the clock. SimpleRateThrottle calls self.timer() for the current time, so unittest.mock.patch can swap that attribute, and the rates dictionary can be patched in the same way.

Python A throttle test that never sleeps

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Output:

TEXT
ran 3 | failures: 0 | errors: 0

A security testing checklist

  • Every endpoint has at least one anonymous test and one wrong-user test.
  • Object-level rules are tested with two users (owner and stranger); the stranger case catches IDOR bugs, where changing an ID in the URL exposes someone else's data.
  • Read-only fields cannot be changed: post {"owner": other_user.id} or {"is_staff": true} and assert it was ignored.
  • Mass assignment: send extra unexpected fields and confirm they are not saved.
  • Login and password-reset endpoints are throttled and do not reveal whether an account exists.
  • Tokens are revoked on logout or password change.
  • Error responses do not leak stack traces or internal IDs (DEBUG=False in the test settings you ship).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is a permission matrix with subTest useful?

    A table is easy to read and extend, and subTest reports each failing row on its own.
  2. 2. What does APIClient(enforce_csrf_checks=True) change?

    By default the test client skips CSRF checks. This option turns the real check back on.
  3. 3. How do you keep a throttle test from sleeping?

    Counters are in the cache, and SimpleRateThrottle reads time through self.timer, which can be patched.
  4. 4. What is an IDOR bug, and which test catches it?

    Insecure direct object reference: the fix is an object-level check, and the stranger test proves it.

Summary

  • Express permission rules as a matrix and loop over it with subTest; test anonymous, owner, stranger and staff.
  • Use force_authenticate for most tests and a few real login-flow tests per authentication scheme.
  • Switch on enforce_csrf_checks=True to test session + CSRF behaviour.
  • Test throttles with cache.clear() and a patched clock; never sleep.
  • Keep a security checklist: IDOR, read-only fields, mass assignment, throttled login, leaked errors.

Next: Query Optimization for DRF APIs