Implementing JWT (JSON Web Token) authentication in Django

Step 1: Install Necessary Packages

First, you need to install the required packages. For JWT authentication in Django, you can use the djangorestframework-simplejwt package.

pip install djangorestframework djangorestframework-simplejwt

Step 2: Configure Django Settings

Add rest_framework and rest_framework_simplejwt to your INSTALLED_APPS in settings.py.

INSTALLED_APPS = [
    ...
    'rest_framework',
    'rest_framework_simplejwt',
    ...
]

Next, configure the REST framework to use JWT for authentication:

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

Step 3: Set Up URLs

In your urls.py, include the views for obtaining and refreshing tokens.

from django.urls import path
from rest_framework_simplejwt.views import (
    TokenObtainPairView,
    TokenRefreshView,
)

urlpatterns = [
    ...
    path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
    ...
]

Step 4: Create Views and Protect Endpoints

Create views and protect your endpoints using the @api_view decorator and the permission_classes attribute.

from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def protected_view(request):
    return Response({'message': 'This is a protected view'})

Step 5: Testing

To test your JWT implementation, you can use tools like Postman or CURL to interact with your API. First, obtain a token by making a POST request to /api/token/ with your username and password.

curl -X POST http://localhost:8000/api/token/ -d "username=yourusername&password=yourpassword"

This will return a response containing the access and refresh tokens. Use the access token to access protected endpoints by including it in the Authorization header.

curl -H "Authorization: Bearer <your_access_token>" http://localhost:8000/protected-endpoint/

Example Project Structure

Here is a basic project structure for reference:

myproject/
    manage.py
    myproject/
        __init__.py
        settings.py
        urls.py
        wsgi.py
    myapp/
        __init__.py
        views.py
        models.py
        urls.py

Example settings.py

# settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'rest_framework_simplejwt',
    'myapp',
]

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

# Additional settings...

Example urls.py

# urls.py

from django.contrib import admin
from django.urls import path
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView
from myapp.views import protected_view

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
    path('protected/', protected_view, name='protected_view'),
]

How It Works

The TokenObtainPairView and TokenRefreshView views provided by djangorestframework-simplejwt are already implemented and ready to use. You do not need to create additional views for these endpoints. They are automatically generated when you include them in your urls.py.

  • TokenObtainPairView: This view is used to obtain a pair of access and refresh tokens. You POST to this endpoint with user credentials (username and password) to get the tokens.
  • TokenRefreshView: This view is used to refresh the access token. You POST to this endpoint with a valid refresh token to get a new access token.

Example Requests

  1. Obtain Token Pair:
    curl -X POST http://127.0.0.1:8000/api/token/ -d "username=myusername&password=mypassword"
    

    This will return a JSON response with access and refresh tokens.

  2. Refresh Token:
    curl -X POST http://127.0.0.1:8000/api/token/refresh/ -d "refresh=your_refresh_token"
    

    This will return a new access token.

Example Response

  • TokenObtainPairView Response:
    {
        "refresh": "your_refresh_token",
        "access": "your_access_token"
    }
    
  • TokenRefreshView Response:
    {
        "access": "your_new_access_token"
    }
    

With these steps, you can seamlessly integrate JWT authentication into your Django application using djangorestframework-simplejwt. There is no need to create additional views for these token endpoints as they are provided out of the box by the package.

Django REST framework with function based view

Setup

  1. Install Django and Django REST framework:
    pip install django djangorestframework
    
  2. Create a new Django project:
    django-admin startproject myproject
    cd myproject
    
  3. Create a new Django app:
    python manage.py startapp myapp
    
  4. Add the app and DRF to INSTALLED_APPS in myproject/settings.py:
    INSTALLED_APPS = [
        ...
        'rest_framework',
        'myapp',
    ]
    

Models

Let’s define a simple model in myapp/models.py:

from django.db import models

class Item(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField()

    def __str__(self):
        return self.name

Run migrations to create the database table:

python manage.py makemigrations
python manage.py migrate

Serializers

Create a serializer for the Item model in myapp/serializers.py:

from rest_framework import serializers
from .models import Item

class ItemSerializer(serializers.ModelSerializer):
    class Meta:
        model = Item
        fields = '__all__'

Views

Create function-based views in myapp/views.py:

from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from .models import Item
from .serializers import ItemSerializer

@api_view(['GET', 'POST'])
def item_list(request):
    if request.method == 'GET':
        items = Item.objects.all()
        serializer = ItemSerializer(items, many=True)
        return Response(serializer.data)
    elif request.method == 'POST':
        serializer = ItemSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

@api_view(['GET', 'PUT', 'DELETE'])
def item_detail(request, pk):
    try:
        item = Item.objects.get(pk=pk)
    except Item.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = ItemSerializer(item)
        return Response(serializer.data)
    elif request.method == 'PUT':
        serializer = ItemSerializer(item, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    elif request.method == 'DELETE':
        item.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

URLs

Define the API endpoints in myapp/urls.py:

from django.urls import path
from . import views

urlpatterns = [
    path('items/', views.item_list),
    path('items/<int:pk>/', views.item_detail),
]

Include the app’s URLs in the project’s urls.py:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('myapp.urls')),
]

Testing the API

Run the development server:

python manage.py runserver

You can now test your API using tools like curl, Postman, or a web browser:

  • GET all items: http://127.0.0.1:8000/api/items/
  • POST a new item: http://127.0.0.1:8000/api/items/ (with JSON data)
  • GET a single item: http://127.0.0.1:8000/api/items/<id>/
  • PUT to update an item: http://127.0.0.1:8000/api/items/<id>/ (with JSON data)
  • DELETE an item: http://127.0.0.1:8000/api/items/<id>/