Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 39 ยท Authentication and Permissions

Token Authentication in DRF

Add token authentication to a Django REST Framework API: the authtoken app, obtain_auth_token, a custom login and logout, automatic tokens with signals, and expiring tokens.

Mobile apps, scripts and single-page applications on another domain cannot rely on a browser session cookie. They need something they can store and send in a header. The simplest option DRF ships with is token authentication: the server creates a random key for each user, the client stores it after logging in, and sends Authorization: Token <key> with every request.

Tokens are easy to understand, easy to revoke (delete the row), and need no CSRF handling. Their downsides are real, too: one token per user by default, no expiry, and a database lookup on every request. Near the end you will fix the expiry problem; the next lesson covers JWT as an alternative.

Setting it up

Token authentication lives in its own app because it needs a table:

Python
# settings.py (read-only)
INSTALLED_APPS = [
    # ...
    "rest_framework",
    "rest_framework.authtoken",
]

REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES": [
        "rest_framework.authentication.TokenAuthentication",
    ],
    "DEFAULT_PERMISSION_CLASSES": ["rest_framework.permissions.IsAuthenticated"],
}

Run python manage.py migrate to create the authtoken_token table. A Token row has three fields: key (40 hex characters, the primary key), user (a one-to-one link) and created.

DRF includes a ready-made login view, obtain_auth_token. It accepts username and password as form data or JSON and returns {"token": "..."}. Wire it to a URL, then try the whole round trip:

Python Log in, receive a token, call the API

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
wrong password: 400 {'non_field_errors': ['Unable to log in with provided credentials.']}
right password: 200 fields: ['token'] key length: 40
no header: 401
with token: {'user': 'mia', 'auth_is_token': True}
garbage token: 401 {'detail': 'Invalid token.'}

The scheme word is literally Token, followed by one space and the key. A header such as Bearer <key> is not accepted by default (you can change it with a subclass that sets keyword = "Bearer").

A better login view

obtain_auth_token only returns the key. Front ends usually want the user's id and name as well, so they do not need a second request. Subclass ObtainAuthToken and also add a logout view that deletes the token, which logs the user out everywhere that token was used.

Another common need is creating the token automatically when a user registers. A post_save signal does that; see Signals for the background.

Python Custom login, logout and automatic tokens

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
tokens right after creating the user: 1
login: 200 {'user_id': 1, 'username': 'mia'}
ping: {'pong': 'mia'}
logout: 204
ping after logout: 401 {'detail': 'Invalid token.'}

Because the signal creates the token on registration, get_or_create in the login view is just a safety net: a user who was created before the signal existed, or whose token was deleted by logout, gets a fresh one on the next login.

Making tokens expire

The stock token never expires. If it leaks, it works until someone deletes it. A simple, honest improvement is to reject tokens older than some limit. Override authenticate_credentials(), which TokenAuthentication calls after it has found the token:

Python An expiring TokenAuthentication subclass

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
fresh token: {'hello': 'mia'}
two days later: 401 {'detail': 'Token has expired. Please log in again.'}
tokens left: 0

Deleting the token when it expires means the client must log in again and receive a brand-new key. A scheduled job that purges old rows (see management commands) keeps the table small.

Security notes

  • Always use HTTPS. A token in a header is a password-equivalent; anyone who can read the request can reuse it.
  • Store it carefully on the client. In a browser, localStorage is readable by any script on the page, so an XSS bug leaks the token. Mobile apps should use the platform's secure storage.
  • Throttle the login view. Without limits, obtain_auth_token lets an attacker guess passwords as fast as the server answers. See Throttling.
  • One token per user means logging in on a phone and a laptop shares the same key, and logging out on one logs out both. If that matters, use JWT or a custom multi-token model.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which header does the default TokenAuthentication expect?

    The keyword is Token followed by a space and the 40-character key. Bearer needs a subclass that changes keyword.
  2. 2. What must you add to INSTALLED_APPS and migrate to use token authentication?

    The Token model lives in the rest_framework.authtoken app, so it needs its own migration.
  3. 3. How do you log a user out of token authentication?

    The key is the only credential. Deleting the row makes every later request with that key fail. Stock tokens never expire on their own.
  4. 4. Where do you put a check that rejects tokens older than a day?

    authenticate_credentials() receives the key and returns (user, token), so you can inspect token.created and raise AuthenticationFailed.

Summary

  • Install rest_framework.authtoken, migrate, and add TokenAuthentication; clients send Authorization: Token <key>.
  • obtain_auth_token exchanges a username and password for a key; subclass ObtainAuthToken to return more data.
  • Create tokens with a post_save signal and delete them to log out.
  • Stock tokens never expire: subclass TokenAuthentication to enforce a maximum age.
  • Use HTTPS and throttle the login endpoint.

Next: JWT Authentication