DRF Authentication
Signup (API)
from django.contrib.auth.models import User
from rest_framework import serializers, viewsets, status
from rest_framework.response import Response
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(
username=validated_data['username'],
email=validated_data['email'],
password=make_password(validated_data['password'])
)
return user
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
return Response(serializer.data, status=status.HTTP_201_CREATED)
Token Authentication
# settings.py
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
],
}
# create token
from rest_framework.authtoken.models import Token
from django.contrib.auth.models import User
user = User.objects.get(username='john')
token = Token.objects.create(user=user)
print(token.key)
Protect API Endpoints
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from rest_framework.response import Response
class HelloView(APIView):
permission_classes = [IsAuthenticated]
def get(self, request):
return Response({"message": f"Hello, {request.user.username}"})
- Client sends token in header:
Authorization: Token <your_token>
Serialiers.py
from rest_framework import serializers
from django.contrib.auth.models import User
from django.contrib.auth import authenticate
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['id', 'username', 'email']
class UserRegistrationSerializer(serializers.ModelSerializer):
password = serializers.CharField(write_only=True)
class Meta:
model = User
fields = ['id', 'username', 'email', 'password' ]
def create(self, validated_data):
user = User(
username=validated_data['username'],
email=validated_data['email']
)
user.set_password(validated_data['password'])
user.save()
return user
class UserLoginSerializer(serializers.Serializer):
username = serializers.CharField(required=True)
password = serializers.CharField(required=True ,write_only=True)
views.py
from django.shortcuts import render
from django.contrib.auth.models import User
from rest_framework import viewsets , generics
from rest_framework.response import Response
from rest_framework import status
from .serializers import UserSerializer , UserRegistrationSerializer , UserLoginSerializer
from rest_framework.permissions import AllowAny
from django.contrib.auth import authenticate
from rest_framework_simplejwt.tokens import RefreshToken
class UserRegistrationViewset(generics.CreateAPIView):
queryset = User.objects.all()
serializer_class = UserRegistrationSerializer
permission_classes = [AllowAny]
class LoginViewset(generics.GenericAPIView):
serializer_class = UserLoginSerializer
def post(self, request, *args, **kwargs):
username = request.data.get('username')
password = request.data.get('password')
user = authenticate(username=username, password=password)
if user is not None:
refresh = RefreshToken.for_user(user)
serializer = UserSerializer(user)
data = {
'refresh': str(refresh),
'access': str(refresh.access_token),
'user': serializer.data
}
return Response(data, status=status.HTTP_200_OK)
else:
return Response({"error": "Invalid credentials"}, status=status.HTTP_401_UNAUTHORIZED)
Urls.py
from django.urls import path , include
from .views import UserRegistrationViewset , LoginViewset
urlpatterns = [
path('register/', UserRegistrationViewset.as_view(), name='user-register'),
path('login/', LoginViewset.as_view(), name='user-login'),
]
link: https://github.com/rafitalavi/jvai_task_1/tree/main/studentmanagement
Comparison Table
|
Feature |
Django |
DRF |
|
Signup |
✅ |
✅ (API) |
|
Login |
✅ |
✅ (Token/JWT) |
|
Session |
✅ |
✅ |
|
Token |
❌ |
✅ |
|
JWT |
❌ |
✅ |
|
Protect View |
@login_required |
IsAuthenticated permission
|