Skip to content
Tutorials Center
My learning

Topics

Lesson 55 of 77 ยท REST APIs

DRF Authentication: Session, Token and JWT

Secure a Django REST Framework API: how session, token and JWT authentication differ, how to set up TokenAuthentication and SimpleJWT obtain/refresh endpoints, and protect views.

An API needs to answer two questions on every request: who is calling (authentication) and are they allowed (authorization, covered in DRF permissions). This lesson is about the first question. DRF treats authentication as a list of pluggable authentication classes. Each class looks at the request and either returns a (user, credentials) pair or declines, and the first class that succeeds wins. If none succeeds, the user is anonymous.

You will meet the three schemes most APIs use, and see each one run in the browser with the real DRF and the real SimpleJWT library.

Choosing a scheme

Scheme Credential on each request Best for
SessionAuthentication The session cookie (plus a CSRF token for unsafe methods) A browser app on the same site as the API
TokenAuthentication Authorization: Token <key> Simple scripts, internal tools, early mobile apps
JWT (SimpleJWT) Authorization: Bearer <access token> Mobile apps and single-page apps on another domain

Session authentication reuses the login you already know from Users and Authentication, and it is the safest choice when your frontend is served from the same domain, because cookies can be HttpOnly. Tokens are for clients that cannot rely on cookies.

Authentication is configured globally and can be overridden per view:

Python
# settings.py (read-only)
REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES": [
        "rest_framework.authentication.SessionAuthentication",
        "rest_framework.authentication.TokenAuthentication",
        "rest_framework_simplejwt.authentication.JWTAuthentication",
    ],
    "DEFAULT_PERMISSION_CLASSES": ["rest_framework.permissions.IsAuthenticated"],
}

Authentication only identifies the caller. Without a permission class such as IsAuthenticated, anonymous requests are still allowed, so you almost always set both.

A failed authentication returns 401 only if the first authentication class supplies a WWW-Authenticate header (token and JWT do; session does not). With session authentication alone, DRF answers 403 instead.

Token authentication

TokenAuthentication stores one random key per user in a database table. You enable it by adding rest_framework.authtoken to INSTALLED_APPS and running migrate. DRF ships a ready-made view, obtain_auth_token, that exchanges a username and password for the key.

Python TokenAuthentication: obtain a token and use it

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.

The token is a database row, so it can be revoked instantly by deleting it. The limits are equally clear: the built-in token never expires, and there is one token per user (logging in on a second device returns the same key). For anything with an expiry or refresh flow, use JWT.

JWT with SimpleJWT

A JSON Web Token is a signed, self-contained string with three dot-separated parts: a header, a payload of claims (who the token is for, when it expires) and a signature. The server does not look anything up to trust it, it only verifies the signature with the secret key. That makes JWTs cheap to check, but also hard to revoke before they expire, so SimpleJWT issues two tokens:

  • a short-lived access token (5 minutes by default) sent on each request, and
  • a longer-lived refresh token (1 day by default) that is only used to get a new access token.
sequenceDiagram
    participant C as Client
    participant A as Django API
    C->>A: POST /jwt/ (username, password)
    A-->>C: access + refresh
    C->>A: GET /me/ (Authorization: Bearer access)
    A-->>C: 200 data
    Note over C,A: access token expires
    C->>A: GET /me/ (expired access)
    A-->>C: 401 token_not_valid
    C->>A: POST /jwt/refresh/ (refresh)
    A-->>C: new access

The client keeps both tokens, sends the access token, and swaps the refresh token for a new access token when a request returns 401.

Install with pip install djangorestframework-simplejwt, put JWTAuthentication in the authentication list, and add two URLs. The example decodes the payload by hand to prove that it is only base64-encoded JSON, readable by anyone. The signature protects it from tampering, not from being read, so never put secrets in a JWT.

Python SimpleJWT: obtain, use, decode, refresh and expire

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.

Production notes for JWT

  • Settings. ROTATE_REFRESH_TOKENS=True issues a new refresh token every time one is used, and BLACKLIST_AFTER_ROTATION=True (with rest_framework_simplejwt.token_blacklist in INSTALLED_APPS) invalidates the old one. A blacklist is how you implement real "log out" and stolen-token response.
  • Where to store tokens. In a browser app, a token in localStorage can be read by any injected script (XSS). Keeping the refresh token in an HttpOnly cookie and the access token in memory is safer. If your frontend and API share a site, plain session authentication avoids the problem entirely. See Security in Django.
  • Use HTTPS only. Bearer tokens are credentials; anyone who captures one can use it.
  • Claims are public. Keep the payload to ids and expiry. Anything sensitive must stay in the database.

Basic authentication

BasicAuthentication implements HTTP Basic: the client sends Authorization: Basic <base64(username:password)> with every request, and DRF checks the pair with Django's authenticate(). It needs no tables beyond the user model, which makes it handy for scripts, internal tools and curl tests.

Python BasicAuthentication step by step

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.

Observe three details. The 401 response carries WWW-Authenticate: Basic realm="api", which is what makes a browser show a login box. Base64 is an encoding, not encryption: anyone who sees the header can read the password, so Basic authentication is acceptable only over HTTPS. And inactive users are rejected like wrong passwords.

In production keep Basic for machine-to-machine calls you control; use tokens or JWT for browser and mobile clients so that the real password is sent once. Behind Apache with mod_wsgi you must also set WSGIPassAuthorization On, otherwise Apache strips the Authorization header before Django sees it. In tests, skip the header altogether with client.force_authenticate(user=...).

Protecting views

Authentication classes can be set per view, and permissions decide the outcome:

Python
# read-only
from rest_framework.permissions import IsAuthenticated
from rest_framework.authentication import SessionAuthentication
from rest_framework_simplejwt.authentication import JWTAuthentication

class ReportViewSet(viewsets.ReadOnlyModelViewSet):
    authentication_classes = [JWTAuthentication, SessionAuthentication]
    permission_classes = [IsAuthenticated]
    serializer_class = ReportSerializer

    def get_queryset(self):
        return Report.objects.filter(owner=self.request.user)   # scope data to the caller

Overriding authentication_classes replaces the global list for that view, so the browsable API (which uses sessions) still works if you list SessionAuthentication as well. Scoping the queryset to request.user is what stops one user from reading another's records.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which authentication scheme is the safest default for a browser frontend served from the same domain as the API?

    HttpOnly session cookies cannot be read by scripts, and CSRF tokens protect unsafe methods. JWTs in localStorage are exposed to XSS.
  2. 2. Why does SimpleJWT issue both an access token and a refresh token?

    A short access lifetime limits the damage if a token leaks, while the long-lived refresh token is used rarely and can be rotated or blacklisted.
  3. 3. Is the payload of a JWT secret?

    Anyone can decode the claims. Never put passwords or private data in a JWT, only identifiers and expiry.
  4. 4. What is a main limitation of DRF's built-in TokenAuthentication?

    The built-in token is a single database row per user that never expires. You can revoke it by deleting the row, but expiry and refresh need JWT or a custom token model.

Summary

  • DRF authentication classes identify the caller; permission classes then decide what they may do, so set both.
  • SessionAuthentication suits same-site browser apps, TokenAuthentication is simple but never expires, and SimpleJWT adds short-lived access tokens plus refresh tokens.
  • JWT payloads are readable by anyone; the signature only guarantees they were not changed.
  • Return 401 with a WWW-Authenticate header when credentials are missing or invalid, and always scope querysets to request.user.
  • Use HTTPS, rotate and blacklist refresh tokens, and think carefully about where the client stores them.

Next: DRF Permissions and Object-Level Permissions.