DRF Authentication: JWT with SimpleJWT & Custom Permissions

APIs consumed by mobile applications (Flutter, React Native) and modern frontend SPAs cannot rely on browser session cookies due to cross-origin limitations. JWT (JSON Web Tokens) with djangorestframework-simplejwt is the industry-standard stateless authentication solution.

1. Configuring SimpleJWT in settings.py

# Install SimpleJWT
pip install djangorestframework-simplejwt
# mywebsite/settings.py
from datetime import timedelta

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    )
}

SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(minutes=30),
    'REFRESH_TOKEN_LIFETIME': timedelta(days=7),
    'ROTATE_REFRESH_TOKENS': True,
    'BLACKLIST_AFTER_ROTATION': True,
    'AUTH_HEADER_TYPES': ('Bearer',),
}

2. Registering Token Endpoints in urls.py

# mywebsite/urls.py
from django.urls import path
from rest_framework_simplejwt.views import (
    TokenObtainPairView,
    TokenRefreshView,
    TokenVerifyView,
)

urlpatterns = [
    # Submit username/password -> returns access & refresh tokens
    path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
    # Submit refresh token -> returns new access token
    path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
    # Verify token validity
    path('api/token/verify/', TokenVerifyView.as_view(), name='token_verify'),
]

3. Building a Custom IsOwnerOrReadOnly Permission Class

# blog/permissions.py
from rest_framework import permissions

class IsOwnerOrReadOnly(permissions.BasePermission):
    """Custom permission to only allow owners of an object to edit or delete it."""

    def has_object_permission(self, request, view, obj):
        # Read permissions are allowed to any request (GET, HEAD, OPTIONS)
        if request.method in permissions.SAFE_METHODS:
            return True

        # Write permissions are only allowed to the author
        return obj.author.user == request.user

Client Request Example

Clients send the access token in the standard HTTP header:
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. Why is JWT preferred over standard TokenAuthentication for mobile and SPA apps?

Standard Django tokens are stateful — every incoming API request requires an SQL query against the `authtoken_token` table to lookup the user. JWT (JSON Web Tokens) are stateless and cryptographically signed; the server verifies the signature mathematically without querying the database on every request, scaling to millions of hits.

Q2. What is the difference between an Access Token and a Refresh Token in SimpleJWT?

An **Access Token** is short-lived (e.g. 15-30 minutes) and sent in the `Authorization: Bearer ` header with every API call. A **Refresh Token** is longer-lived (e.g. 7-14 days) and is used exclusively against `/api/token/refresh/` to obtain a fresh access token without asking the user to re-type their credentials.

Q3. What is IsOwnerOrReadOnly permission in DRF?

`IsOwnerOrReadOnly` is a standard custom permission class that permits safe HTTP methods (GET, HEAD, OPTIONS) to any user, but restricts write operations (PUT, PATCH, DELETE) to the author/owner of the object.

Q4. How do you install SimpleJWT?

Run `pip install djangorestframework-simplejwt` and register `'rest_framework_simplejwt'` in `settings.py`.

Explore Related Django Tutorials & Next Steps

Broaden your backend architecture, REST API design, and production engineering expertise:

DRF ViewSets & Routers

Protect API endpoints from unauthorized client access.

Custom User Model (AbstractUser)

Generate JWT tokens containing custom user claims and roles.

Django Security Hardening

Protect JWT tokens from interception and implement token rotation.

130+ Django Interview Questions

Technical interview questions on session auth vs token auth vs JWT.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Reddit

You may also like this!