Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 39 ยท Authentication and Permissions

Authentication Schemes in DRF

Learn how Django REST Framework identifies the caller: request.user and request.auth, Basic and Session authentication, CSRF rules, 401 versus 403, and a custom API-key scheme.

Every API request arrives with a question attached: who is calling? Django REST Framework answers it in a step called authentication. The step does not decide whether the caller may do anything. It only fills in two attributes on the request, request.user and request.auth. What the caller is allowed to do is the job of permissions, which run right after.

This lesson shows how DRF walks through its list of authentication classes, what the built-in Basic and Session schemes do, why a failed login sometimes returns 401 and sometimes 403, and how to write your own scheme in about fifteen lines. All examples run in your browser with a real Django and DRF.

The examples here start a tiny Django project inside your browser tab (SQLite in memory, packages installed from PyPI the first time you press Run). Settings such as ROOT_URLCONF = "project" and the sys.modules clean-up at the top exist only so the demo can run again and again. In your own project those lines live in settings.py and urls.py.

How DRF authenticates a request

Each view has a list of authentication classes. On the first access to request.user, DRF tries them in order:

  1. Call authenticate(request) on the first class.
  2. If it returns None, the class "does not apply" (for example, the header it looks for is missing). Try the next class.
  3. If it returns a (user, auth) pair, stop. request.user and request.auth are set from that pair.
  4. If it raises AuthenticationFailed, stop at once and return an error. The caller sent credentials, but they were wrong.
  5. If every class returned None, the request is anonymous: request.user is an AnonymousUser and request.auth is None.
flowchart LR
    R["Request"] --> A1["Authentication class 1"]
    A1 -->|"None"| A2["Authentication class 2"]
    A1 -->|"user, auth"| OK["request.user is set"]
    A1 -->|"AuthenticationFailed"| E["401 or 403"]
    A2 -->|"None"| AN["AnonymousUser"]
    A2 -->|"user, auth"| OK
    OK --> P["Permission classes"]
    AN --> P

An authentication class either claims the request, skips it or rejects it.

You set the classes for the whole project in settings.py, or per view with authentication_classes:

Python
# settings.py (read-only)
REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES": [
        "rest_framework.authentication.SessionAuthentication",
        "rest_framework.authentication.BasicAuthentication",
    ],
}

If you set nothing, DRF uses SessionAuthentication and BasicAuthentication, in that order.

request.user and request.auth

The two values mean different things depending on the scheme:

Scheme request.user request.auth
BasicAuthentication the User row None
SessionAuthentication the User row None
TokenAuthentication the User row the Token object
JWT the User row the validated token
your own scheme anything you return anything you return

Basic authentication

HTTP Basic sends Authorization: Basic base64(username:password) with every request. It is simple and needs no state, but the password travels on every call, so it is only acceptable over HTTPS and is mostly used for scripts, internal tools and tests.

Python Basic authentication and the 401 response

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.'} | WWW-Authenticate: Basic realm="api"
right password -> 200 {'user': 'mia', 'auth': None} | WWW-Authenticate: None
wrong password -> 401 {'detail': 'Invalid username/password.'} | WWW-Authenticate: Basic realm="api"

Two different failures appear above. With no credentials the request is anonymous and the permission class refuses it: Authentication credentials were not provided. With wrong credentials the authentication class itself rejects it. Both are 401 here because Basic is the first class and provides a WWW-Authenticate header, which tells a browser or client how to authenticate.

Session authentication and CSRF

SessionAuthentication reuses Django's normal login session: the browser sends the sessionid cookie, and DRF reads request.user from Django's AuthenticationMiddleware. It is the right choice when your JavaScript front end is served from the same site as the API, including the browsable API.

Because cookies are sent automatically by browsers, session-authenticated unsafe requests (POST, PUT, PATCH, DELETE) must carry a CSRF token, otherwise another website could trick a logged-in browser into submitting them. DRF enforces this for you, only for session-authenticated requests. Token and JWT requests need no CSRF token because the browser never attaches those headers by itself.

Python Session login and the CSRF check

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
anonymous GET: 403 {'detail': 'Authentication credentials were not provided.'}
logged-in GET: {'hello': 'mia'}
POST without a CSRF token: 403 {'detail': 'CSRF Failed: CSRF cookie not set.'}
POST with CSRF checks off: 200 {'received': {'note': 'hi'}}

In a real front end you read the csrftoken cookie and send it back in the X-CSRFToken header (see CSRF protection). The browsable API does that for you.

401 or 403?

DRF picks the status code from the first authentication class in the list:

  • If that class defines authenticate_header() (Basic, Token, JWT do), failures return 401 Unauthorized with a WWW-Authenticate header.
  • If it does not (Session does not), DRF falls back to 403 Forbidden, because there is nothing useful to put in the header.

So a project that lists SessionAuthentication first will answer 403 to anonymous calls, while one that lists TokenAuthentication first answers 401. Front-end code usually handles both the same way: send the user to the login screen.

Writing a custom scheme

When none of the built-in schemes fit (an API key in a custom header, a signed request from another service, a legacy token format), subclass BaseAuthentication and implement authenticate(). Remember the three outcomes: return None to skip, return (user, auth) to succeed, raise AuthenticationFailed to reject.

Python A custom API-key authentication class

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 header  401 {'detail': 'Authentication credentials were not provided.'} ApiKey
bad key    401 {'detail': 'Invalid API key.'} ApiKey
good key   200 {'user': 'mia', 'key_used': 'key-mia-123'} None

Notice that the class returns None when the header is missing. That is what lets you stack it with other schemes: authentication_classes = [ApiKeyAuthentication, SessionAuthentication] accepts either an API key or a browser session.

Common mistakes

  • Treating authentication as authorization. Authentication only identifies the caller. Without a permission class (or a DEFAULT_PERMISSION_CLASSES setting) an anonymous caller still reaches the view.
  • Raising AuthenticationFailed when the header is simply absent. That blocks the next scheme in the list and makes mixed schemes impossible. Return None.
  • Using Basic or tokens over plain HTTP. Anyone on the network can read them. Always serve APIs over HTTPS.
  • Disabling CSRF on session-authenticated endpoints. @csrf_exempt on a DRF view does not help (DRF re-checks), and the right fix is to send the token or to use a header-based scheme.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does authenticate() return when the credentials it looks for are missing from the request?

    None means 'not my scheme'. DRF then tries the next class, and falls back to an anonymous request if none applies.
  2. 2. Why does an anonymous request to a view that lists SessionAuthentication first get a 403 and not a 401?

    A 401 response must carry a WWW-Authenticate header. The first class decides it, and SessionAuthentication has none, so DRF returns 403.
  3. 3. Which requests does DRF protect with a CSRF check?

    Browsers attach cookies automatically, so only session-authenticated POST, PUT, PATCH and DELETE need the token. Header-based schemes are not vulnerable in the same way.
  4. 4. What is stored in request.auth after a successful Basic authentication?

    BasicAuthentication returns (user, None). Token-based schemes put the token object in request.auth.

Summary

  • Authentication fills request.user and request.auth; permissions decide what the caller may do.
  • Classes are tried in order: None skips, (user, auth) succeeds, AuthenticationFailed rejects.
  • Basic sends the password every time, Session needs CSRF tokens for unsafe methods, Token and JWT use an Authorization header.
  • The first class's authenticate_header() decides between 401 and 403.
  • A custom scheme is a BaseAuthentication subclass with authenticate().

Next: Token Authentication