Django JWT API Token Authentication: Login, Register & Dashboard

Author

DevDuniya

Mar 26, 2025

Django JWT API Token Authentication: Login, Register & Dashboard

In this comprehensive guide, we'll build a Django REST API with JWT (JSON Web Token) authentication, covering user registration, login, and a protected dashboard. JWT authentication is widely used in modern web and mobile applications because of its stateless nature and security benefits.

By the end of this tutorial, you'll have a fully functional Django REST API that:
โœ… Allows users to register and login using JWT tokens
โœ… Secures API endpoints with token-based authentication
โœ… Provides a protected dashboard for authenticated users


Why Use JWT Authentication in Django?

JWT (JSON Web Token) authentication is a popular, secure, and scalable way to handle API authentication. Hereโ€™s why you should use it:

๐Ÿ”น Stateless: No need to store tokens on the server (unlike session-based auth).
๐Ÿ”น Secure: Tokens are digitally signed and can include expiration.
๐Ÿ”น Scalable: Works well with microservices and mobile apps.
๐Ÿ”น Flexible: Can be used across different platforms (web, mobile, IoT).

Django REST Framework (DRF) with SimpleJWT makes JWT implementation seamless.


Prerequisites

Before we start, ensure you have:

  • Python 3.6+ installed
  • Django & Django REST Framework installed
  • Basic knowledge of Django models, views, and serializers

Step 1: Setting Up the Django Project

1. Create a Virtual Environment & Install Dependencies

python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

2. Install Required Packages

pip install django djangorestframework djangorestframework-simplejwt

3. Create a Django Project & App

django-admin startproject jwt_auth_project
cd jwt_auth_project
python manage.py startapp accounts

4. Update settings.py for JWT Authentication

Add the following to jwt_auth_project/settings.py:

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

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

# JWT Settings
from datetime import timedelta

SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(minutes=30),
    'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
}

5. Run Migrations & Create Superuser

python manage.py migrate
python manage.py createsuperuser  # For admin access

Step 2: Creating the User Model & Serializers

1. Custom User Model (Optional but Recommended)

In accounts/models.py:

from django.contrib.auth.models import AbstractUser
from django.db import models

class CustomUser(AbstractUser):
    email = models.EmailField(unique=True)
    
    def __str__(self):
        return self.username

Update settings.py to use the custom model:

AUTH_USER_MODEL = 'accounts.CustomUser'

Run migrations:

python manage.py makemigrations
python manage.py migrate

2. Create Serializers for User Registration & Login

In accounts/serializers.py:

from rest_framework import serializers
from django.contrib.auth import get_user_model
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer

User = get_user_model()

class UserRegisterSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True)
    
    class Meta:
        model = User
        fields = ['username', 'email', 'password']
    
    def create(self, validated_data):
        user = User.objects.create_user(
            username=validated_data['username'],
            email=validated_data['email'],
            password=validated_data['password']
        )
        return user

class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
    @classmethod
    def get_token(cls, user):
        token = super().get_token(user)
        token['username'] = user.username
        return token

Step 3: Building API Views

1. User Registration & Login Views

In accounts/views.py:

from rest_framework import generics, status
from rest_framework.response import Response
from rest_framework_simplejwt.views import TokenObtainPairView
from .serializers import UserRegisterSerializer, MyTokenObtainPairSerializer

class RegisterView(generics.CreateAPIView):
    queryset = User.objects.all()
    serializer_class = UserRegisterSerializer

class LoginView(TokenObtainPairView):
    serializer_class = MyTokenObtainPairSerializer

2. Protected Dashboard View (Token Required)

from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView

class DashboardView(APIView):
    permission_classes = [IsAuthenticated]
    
    def get(self, request):
        user = request.user
        data = {
            "message": f"Welcome, {user.username}!",
            "email": user.email,
            "last_login": user.last_login
        }
        return Response(data)

Step 4: Setting Up URLs

1. Update jwt_auth_project/urls.py

from django.contrib import admin
from django.urls import path, include
from rest_framework_simplejwt.views import TokenRefreshView
from accounts.views import RegisterView, LoginView, DashboardView

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/register/', RegisterView.as_view(), name='register'),
    path('api/login/', LoginView.as_view(), name='login'),
    path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
    path('api/dashboard/', DashboardView.as_view(), name='dashboard'),
]

Step 5: Testing the API

1. Start the Development Server

python manage.py runserver

2. Register a New User (POST Request)

Endpoint: http://127.0.0.1:8000/api/register/

Request Body (JSON):

{
    "username": "testuser",
    "email": "test@example.com",
    "password": "securepassword123"
}

3. Login & Get JWT Tokens (POST Request)

Endpoint: http://127.0.0.1:8000/api/login/

Response:

{
    "refresh": "xxxxx.yyyyy.zzzzz",
    "access": "aaaaa.bbbbb.ccccc"
}

4. Access Protected Dashboard (GET Request with Token)

Headers:

{
    "Authorization": "Bearer aaaaa.bbbbb.ccccc"
}

Response:

{
    "message": "Welcome, testuser!",
    "email": "test@example.com",
    "last_login": "2023-10-01T12:00:00Z"
}

Conclusion

Weโ€™ve successfully built a Django REST API with JWT authentication, including:

โœ… User registration
โœ… JWT-based login
โœ… Token refresh
โœ… Protected dashboard endpoint

This setup is production-ready and can be extended with:

๐Ÿ”น Password reset functionality
๐Ÿ”น Email verification
๐Ÿ”น Social authentication (Google, Facebook, etc.)

By using Django REST Framework and SimpleJWT, weโ€™ve ensured security, scalability, and ease of integration with frontend frameworks like React, Vue, or Angular.


Next Steps

  1. Integrate with a frontend framework (React, Vue, Angular).
  2. Add email verification for user registration.
  3. Implement rate limiting to prevent brute-force attacks.
  4. Deploy the API using Django + Gunicorn + Nginx.

Tags

Python Coding Programming

Related Posts