Basic and Session Authentication in DRF
Authentication and permissions are essential aspects of building secure APIs with Django Rest Framework (DRF). In this tutorial, we will focus on implementing Session Authentication and Basic Authentication while incorporating permissions to control access to API resources.
Basic Authentication
Basic Authentication involves sending user credentials (username and password) as a base64-encoded string with each request. To use Basic Authentication update your views.py file according to the code given below.
views.py
from rest_framework.generics import ListAPIView, CreateAPIView
from .models import Students
from .serializers import StudentsSerializer
from rest_framework.authentication import BasicAuthentication
from rest_framework.permissions import IsAuthenticated
class StudentsListCreateView(ListAPIView, CreateAPIView):
queryset = Students.objects.all()
serializer_class = StudentsSerializer
authentication_classes = [BasicAuthentication]
permission_classes = [IsAuthenticated]
The authentication part in this view ensures that users accessing the endpoint must provide valid Basic Authentication credentials to create and access students records.
Output:
Session Authentication
Session Authentication is suitable for web applications that utilize session cookies for user authentication.
views.py
from rest_framework.generics import ListAPIView, CreateAPIView
from .models import Students
from .serializers import StudentsSerializer
from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import IsAuthenticated
class StudentsListCreateView(ListAPIView, CreateAPIView):
queryset = Students.objects.all()
serializer_class = StudentsSerializer
authentication_classes = [SessionAuthentication]
permission_classes = [IsAuthenticated]
The above code enables authenticated users to list and create student records using Session Authentication in DRF. To authenticate users, we have create a login view to validate credentials and log users in, utilizing Django's session management.
Output: