1. Home
  2. Docs
  3. Django Rest Framework
  4. Authentication

Authentication

Main Branch

Step 0 : প্রথমে পাইথন ইনস্টল করি

link follow

Step 1: Create a new Django project and virtual environment

# Create a virtual environment (optional but recommended)
python -m venv django-api
# Activate the virtual environment
source django-api/bin/activate  # On Windows: venv\Scripts\activate

# Install Django
pip install django

# Create a new Django project
django-admin startproject djangoapi
cd djangoapi
Bash

Step 2: Install Django Rest Framework and Django Rest Framework Simple JWT

# Install Django Rest Framework
pip install djangorestframework

# Install Django Rest Framework Simple JWT
pip install djangorestframework-simplejwt

#django-cors-headers প্যাকেজ ইনস্টল করতে হবে
pip install django-cors-headers
Bash

Step 3: Configure your Django project settings

Add 'rest_framework' and 'rest_framework_simplejwt' to the INSTALLED_APPS in your settings.py file.

# djangoapi/settings.py

INSTALLED_APPS = [
    # ...
    'corsheaders',
    'rest_framework',
    'rest_framework_simplejwt',
    'rest_framework_simplejwt.token_blacklist', 
    # ...
]



MIDDLEWARE = [

# ...

'corsheaders.middleware.CorsMiddleware',

# ...

]

CORS_ALLOW_ALL_ORIGINS = True

Python

Step 4: Configure Django Rest Framework

Update your settings.py to include the following configurations:

# Set the token expiration time
from datetime import timedelta
SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(minutes=15),  # Adjust as needed
    'REFRESH_TOKEN_LIFETIME': timedelta(days=1),     # Adjust as needed
    'BLACKLIST_AFTER_ROTATION': True,
    'UPDATE_LAST_LOGIN': True,

    # Add the below blacklist configurations
    'BLACKLIST_ENABLE': True,
    'BLACKLIST_ALGORITHM': 'jwt_token_blacklist.algorithms.RevocationListJSONWebToken',
    'AUTH_HEADER_TYPES': ('Bearer',),
}

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

python manage.py migrate
Python

এবার গিট্ এ যোগ করি main ব্রাঞ্চ হিসাবে

Authentication

Create a Django app for authentication

# Create a new app for authentication
python manage.py startapp authentication
Python

Configure Settings.py

INSTALLED_APPS = [
    'authentication',
]
Python

Create serializers for user registration

# authentication/serializers.py

from rest_framework import serializers
from django.contrib.auth.models import User

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id', 'username', 'email', 'password']
        extra_kwargs = {'password': {'write_only': True}}

    def create(self, validated_data):
        user = User.objects.create_user(
            username=validated_data['username'],
            email=validated_data['email'],
            password=validated_data['password']
        )
        return user
Python

# authentication/views.py

from rest_framework import generics, status
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework_simplejwt.tokens import RefreshToken
from django.contrib.auth.models import User
from django.contrib.auth import authenticate
from .serializers import UserSerializer

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

class LoginView(APIView):
    permission_classes = [AllowAny]

    def post(self, request):
        email = request.data.get('email')
        password = request.data.get('password')

        # Custom authentication using email
        user = User.objects.filter(email=email).first()

        if user is not None and user.check_password(password):
            refresh = RefreshToken.for_user(user)
            access_token = refresh.access_token

            return Response({'access_token': str(access_token), 'refresh_token': str(refresh),
                             'id': user.id, 'username': user.username, 'email': user.email})
        else:
            return Response({'detail': 'Invalid credentials'}, status=status.HTTP_401_UNAUTHORIZED)
        

class LogoutView(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request):
        try:
            refresh_token = request.data.get('refresh_token')
            token = RefreshToken(refresh_token)
            token.blacklist()

            return Response({'detail': 'Successfully logged out'}, status=status.HTTP_200_OK)
        except Exception as e:
            return Response({'detail': 'Invalid token or token has already been used'}, status=status.HTTP_400_BAD_REQUEST)
Python

Configure authentication app URLs

Create a urls.py file inside the authentication app and configure the authentication endpoints:

# authentication/urls.py

from django.urls import path
from .views import RegisterView, LoginView, LogoutView

urlpatterns = [
    path('register/', RegisterView.as_view(), name='register'),
    path('login/', LoginView.as_view(), name='login'),
    path('logout/', LogoutView.as_view(), name='logout'),
]
Python

Configure authentication app views in project URLs

Include the authentication app URLs in the main urls.py of your project:

# yourproject/urls.py

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

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

Check Api

python manage.py runserver
Python

Testing User Registration:

  • Create a new request in Postman.
  • Set the request type to POST.
  • Enter the URL: http://localhost:8000/api/users/register/.
  • In the request body, choose raw and set the content type to JSON (application/json).
  • Provide user registration data in JSON format. For example:
{
  "username": "olee",
  "email": "olee.techs@gmail.com",
  "password": "1234"
}
Python

Testing User Login:

  • Create another request in Postman.
  • Set the request type to POST.
  • Enter the URL: http://localhost:8000/api/users/login/.
  • In the request body, choose raw and set the content type to JSON (application/json).
  • Provide login credentials in JSON format. For example:
{
  "email": "olee.techs@gmail.com",
  "password": "1234"
}
Python

Testing User Logout:

  • Create a new request in Postman.
  • Set the request type to POST.
  • Enter the URL: http://localhost:8000/api/users/logout/.
  • In the request body, choose raw and set the content type to JSON (application/json).
  • Provide the refresh_token obtained during login in JSON format. For example:

How can we help?