Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 39 ยท Authentication and Permissions

JWT Authentication with Simple JWT

Secure a Django REST Framework API with JSON Web Tokens using djangorestframework-simplejwt: access and refresh tokens, custom claims, expiry, rotation and blacklisting.

A JSON Web Token (JWT) is a signed string that carries claims about the user: who they are, when the token expires, and anything else you add. Because the server signs it, the server can verify it without a database lookup, which is why JWTs are popular for mobile apps, single-page applications and services that call each other.

DRF does not include JWT support. The community package djangorestframework-simplejwt is the standard choice, and this lesson uses it. You will log in, inspect a token, see what an expired one does, and use refresh rotation with a blacklist.

Anatomy of a JWT

A JWT is three Base64URL parts joined by dots: header.payload.signature.

flowchart LR
    H["Header: algorithm HS256, type JWT"] --- P["Payload: user_id, exp, token_type, jti"] --- S["Signature: HMAC of header and payload with SECRET_KEY"]

Anyone can read the payload; only the holder of the secret can produce a valid signature.

The payload is not encrypted. Never put passwords, personal data or secrets in a claim. The signature only guarantees that the content was not changed.

Simple JWT issues two kinds of token:

Token Lifetime (default) Purpose
access 5 minutes Sent on every API call in Authorization: Bearer <access>
refresh 1 day Sent only to the refresh endpoint to get a new access token

Short-lived access tokens limit the damage of a leak; the longer refresh token keeps the user logged in without typing the password again.

Setup

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

REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES": [
        "rest_framework_simplejwt.authentication.JWTAuthentication",
    ],
}

# urls.py (read-only)
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView

urlpatterns = [
    path("api/token/", TokenObtainPairView.as_view()),
    path("api/token/refresh/", TokenRefreshView.as_view()),
]

TokenObtainPairView takes username and password and returns {"refresh": ..., "access": ...}. TokenRefreshView takes a refresh token and returns a new access token.

Log in, call the API, add custom claims

You can add your own claims to the token by subclassing TokenObtainPairSerializer. Keep claims small and non-sensitive, since they travel with every request.

Python Obtain, decode and use a JWT

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
login: 200 ['access', 'refresh']
access has 3 dot-separated parts: 3
claims: ['exp', 'iat', 'jti', 'token_type', 'user_id', 'username']
token_type: access | username: mia | lifetime: 300 seconds
no header: 401
with access token: {'user': 'mia', 'auth_type': 'AccessToken'}
refresh: 200 ['access']
refresh token used as access: 401 token_not_valid

The last line shows a classic mistake: a refresh token is valid, but it is the wrong type for protecting API calls, so Simple JWT rejects it.

Expired tokens

Lifetimes and many other behaviours are configured in a SIMPLE_JWT dictionary. The next example sets the access lifetime to a negative value so every token is already expired, which lets you see the error response without waiting five minutes.

Python What an expired access token looks like

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
expired access: 401
  code: token_not_valid
  messages: ['Token is expired']
  WWW-Authenticate: Bearer realm="api"
refresh works while the refresh token is valid: 200 ['access']

A well-behaved client handles 401 with code: token_not_valid by calling the refresh endpoint once, replacing its stored access token and repeating the failed request. If the refresh call fails as well, it sends the user to the login screen.

Rotation and the blacklist

A refresh token that lives for a day is a juicy target. Simple JWT can limit that with two settings:

  • ROTATE_REFRESH_TOKENS = True: every refresh returns a new refresh token too.
  • BLACKLIST_AFTER_ROTATION = True: the old refresh token is put on a blacklist, so a stolen copy stops working as soon as the real user refreshes.

The blacklist is a database table, so you add the rest_framework_simplejwt.token_blacklist app and migrate. The same app lets you blacklist a refresh token explicitly, which is how you implement logout for JWT.

Python Refresh rotation with a blacklist

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
first refresh: 200 ['access', 'refresh']
a new refresh token was issued: True
reusing the old refresh token: 401 Token is blacklisted
logout with the current refresh token: 205
refresh after logout: 401 Token is blacklisted

Remember what blacklisting does not do: an access token that is already issued stays valid until it expires. That is why access lifetimes are short. If you must cut off a user immediately, check an extra condition in a custom authentication class or in a permission.

JWT or token authentication?

DRF TokenAuthentication JWT (Simple JWT)
Lookup per request One database query None for access tokens (signature check only)
Revocation Delete the row; instant Access tokens live until expiry; refresh tokens can be blacklisted
Expiry Not built in Built in
Payload None Claims you choose
Complexity Very low Moderate (two tokens, refresh flow)

Pick plain tokens for small internal APIs and scripts. Pick JWT when many clients call the API at scale, or several services must verify the same login without sharing a database.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is it a bad idea to put a user's home address in a JWT claim?

    A JWT is signed, not encrypted. The signature prevents tampering but not reading.
  2. 2. Which header carries the access token by default in Simple JWT?

    Simple JWT's AUTH_HEADER_TYPES defaults to Bearer.
  3. 3. What do ROTATE_REFRESH_TOKENS and BLACKLIST_AFTER_ROTATION achieve together?

    A stolen refresh token becomes useless once the real user refreshes, because the old one is blacklisted.
  4. 4. A user logs out and you blacklist their refresh token. What happens to an access token issued a minute earlier?

    Access tokens are verified by signature only, so they stay valid until their exp time. Keep their lifetime short.

Summary

  • A JWT is a signed, readable token; the server verifies it without a database query.
  • Simple JWT issues a short-lived access token for API calls (Bearer) and a longer-lived refresh token for getting new access tokens.
  • Add custom claims in get_token(); keep them small and non-sensitive.
  • Expired access tokens return 401 with code: token_not_valid; clients refresh and retry.
  • Rotation plus the blacklist app limits stolen refresh tokens and gives you JWT logout.

Next: Permission Classes