
Django Rest Framework (DRF) provides several built-in authentication classes, including session authentication. Session authentication allows users to authenticate by using Django’s built-in session framework, which relies on a session ID cookie that is sent with each HTTP request.
To enable session authentication in DRF, you need to include the SessionAuthentication
class in the DEFAULT_AUTHENTICATION_CLASSES
list in your DRF settings. For example:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
)
}
Once session authentication is enabled, users can authenticate by logging in via a Django view or by including the session ID cookie with their requests. DRF will automatically use the SessionAuthentication backend to authenticate requests that include the session ID cookie.
A simple project on session authentication in Django Rest Framework:
1. Create a new Django project using the following command:
django-admin startproject myproject
2. Create a new Django app using the following command:
python manage.py startapp myapp
3. Install Django Rest Framework by running the following command:
pip install djangorestframework
4. In your myproject/settings.py
file, add rest_framework
to your INSTALLED_APPS
list:
INSTALLED_APPS = [
# ...
'rest_framework',
]
5. In your myapp/views.py
file, create a simple API view that requires authentication:
from rest_framework.decorators import api_view, authentication_classes, permission_classes
from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
@api_view(['GET'])
@authentication_classes([SessionAuthentication])
@permission_classes([IsAuthenticated])
def my_view(request):
content = {'message': 'Hello, world!'}
return Response(content)
6. In your myproject/urls.py
file, create a URL pattern for your API view:
from django.urls import path
from myapp.views import my_view
urlpatterns = [
path('my-api/', my_view, name='my-api'),
]
7. In your myproject/settings.py
file, add rest_framework.authentication.SessionAuthentication
to your DEFAULT_AUTHENTICATION_CLASSES
list:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.SessionAuthentication',
]
}
8. Run the server using the following command:
python manage.py runserver
9. Open a web browser and navigate to http://127.0.0.1:8000/my-api/
. You should be redirected to the login page. Log in with a valid user account, and you should be able to access the API view.
That’s it! This is a simple project that demonstrates how to implement SessionAuthentication in Django Rest Framework.
Github Link: