Skip to content
Araz Shah
Menu
  • Home
  • About me
  • Contact me
  • CV
  • Online Courses
    • Apply Now !
    • In-Depth
    • Courses
      • Concepts
      • Python Course
      • GIS Developer Course
    • Price
Menu

Django. JWT (JSON Web Tokens)

Posted on September 3, 2023 by admin

Django Rest Framework (DRF) is a powerful toolkit for building Web APIs in Django. JWT (JSON Web Tokens) is a popular authentication method for securing RESTful APIs. Here, I’ll provide you with an example of how to implement JWT authentication in a Django Rest Framework project.

First, make sure you have Django and Django Rest Framework installed. You can install them using pip if you haven’t already:

pip install django djangorestframework djangorestframework-jwt

Next, create a new Django project or use an existing one. For this example, we’ll create a new project and a sample app.

  1. Create a new Django project and a sample app:
django-admin startproject myproject
cd myproject
python manage.py startapp myapp
  1. Configure Django settings for the app:

In your project’s settings.py, add 'rest_framework' and 'myapp' to the INSTALLED_APPS:

INSTALLED_APPS = [
    # ...
    'rest_framework',
    'myapp',
    # ...
]
  1. Configure Django Rest Framework settings:

In the same settings.py file, add the following configurations:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
    ),
}

JWT_AUTH = {
    'JWT_SECRET_KEY': 'your-secret-key',  # Change this to your own secret key.
    'JWT_ALGORITHM': 'HS256',
    'JWT_ALLOW_REFRESH': True,
    'JWT_REFRESH_EXPIRATION_DELTA': timedelta(days=7),
}

Replace 'your-secret-key' with a strong, secret key for your application.

  1. Create a user model:

In your myapp/models.py, define a custom user model or use Django’s built-in User model:

from django.contrib.auth.models import AbstractUser

class CustomUser(AbstractUser):
    # Add any additional fields you need
    pass
  1. Create serializers and views:

Create serializers for your data and views for your API endpoints in your myapp app.

  1. Configure URLs:

In your myapp/urls.py, configure the URLs for your views:

from django.urls import path
from myapp import views

urlpatterns = [
    path('api/token/', views.CustomTokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('api/token/refresh/', views.CustomTokenRefreshView.as_view(), name='token_refresh'),
    # Add your other API endpoints here
]
  1. Create JWT views:

In your myapp/views.py, create custom JWT views using Django Rest Framework’s TokenObtainPairView and TokenRefreshView:

from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView
from .serializers import CustomTokenObtainPairSerializer

class CustomTokenObtainPairView(TokenObtainPairView):
    serializer_class = CustomTokenObtainPairSerializer

class CustomTokenRefreshView(TokenRefreshView):
    pass
  1. Create a serializer for the token:

In your myapp/serializers.py, create a custom serializer for the token:

from rest_framework_simplejwt.serializers import TokenObtainPairSerializer

class CustomTokenObtainPairSerializer(TokenObtainPairSerializer):
    # Add any additional fields you need here
    pass
  1. Migrate the database:

Run the following commands to create the necessary database tables:

python manage.py makemigrations
python manage.py migrate
  1. Create a superuser:

Create a superuser to access the Django admin site and test your API:

python manage.py createsuperuser
  1. Test your API:

Start the development server:

python manage.py runserver

You can now test your API using tools like curl, httpie, or a frontend client.

To obtain a JWT token, make a POST request to the /api/token/ endpoint with your superuser’s credentials. Then, you can use the token for authentication in your API requests.

Remember to handle token expiration and refresh as needed in your frontend or client application.

Category: python, Tutorials

Post navigation

← IoT data storage
Django and InfluxDB to save sensor data →

Recent Posts

  • Geospatial Risk Assessment: A Python Approach
  • Analyzing Employee Arrival Patterns and Delays Using Geospatial Data
  • Real-Time GPS Tracking on a Web Map using FastAPI & Leaflet
  • How to Create a Simple WebGIS with FastAPI, PostGIS, and Leaflet.js
  • Graph Coloring: How Many Colors Do You Need?

Archives

  • May 2025
  • February 2025
  • January 2025
  • December 2024
  • November 2024
  • September 2024
  • April 2024
  • March 2024
  • February 2024
  • December 2023
  • October 2023
  • September 2023
  • August 2023
  • April 2023

Categories

  • Courses
  • Events
  • GIS
  • Linux
  • News
  • programming
  • python
  • Tutorials
  • Videos
  • May 2025
  • February 2025
  • January 2025
  • December 2024
  • November 2024
  • September 2024
  • April 2024
  • March 2024
  • February 2024
  • December 2023
  • October 2023
  • September 2023
  • August 2023
  • April 2023
  • Courses
  • Events
  • GIS
  • Linux
  • News
  • programming
  • python
  • Tutorials
  • Videos

Araz Shahkarami

I’m a software enthusiast with a deep love for crafting robust and efficient solutions. My journey into the world of programming began several years ago when I was introduced to the world of code. Since then, I’ve been on an exhilarating ride of learning, problem-solving, and continuous improvement.

© 2025 Araz Shah | Powered by Minimalist Blog WordPress Theme