Basic Authentication in Django Rest Framework (DRF) with Examples

Authentication is a crucial aspect of web applications that ensures only authorized users can access certain resources or perform specific actions. In Django Rest Framework (DRF), an excellent tool for building RESTful APIs in Django, you have various authentication methods at your disposal. One of the simplest and most commonly used methods is Basic Authentication. In this blog, we’ll explore Basic Authentication in DRF and provide examples to help you understand its implementation.

  1. Basic Authentication: Uses username and password for simple API authentication.
  2. Session Authentication: Integrates with Django’s session-based authentication for web and API security.
  3. Token Authentication: Provides stateless token-based authentication for secure API access.
  4. Remote User Authentication: Method of authenticating users in Django where user credentials are managed by a separate authentication system

What is Basic Authentication?

Basic Authentication is a straightforward authentication mechanism where the client sends a username and password with each HTTP request. These credentials are typically Base64-encoded and included in the request’s Authorization header. While Basic Authentication is simple to implement, it is essential to use it securely, often over an HTTPS connection, to prevent exposing user credentials in plaintext.

Implementing Basic Authentication in DRF:

Let’s walk through the steps to implement Basic Authentication in a DRF project.

Step 1 – Install Django Rest Framework: If you haven’t already, install DRF using pip:

pip install djangorestframework

Step 2 – Configure DRF in Django Project : Add ‘rest_framework’ to your Django project’s settings:

INSTALLED_APPS = [
    # ...
    'rest_framework',
]

Step 3 – Create a Serializer and ViewSet: Define a serializer to serialize your data and a ViewSet to handle CRUD operations. For example, let’s create a simple API for managing tasks:

from rest_framework import serializers, viewsets
from .models import Task

class TaskSerializer(serializers.ModelSerializer):
    class Meta:
        model = Task
        fields = '__all__'

class TaskViewSet(viewsets.ModelViewSet):
    queryset = Task.objects.all()
    serializer_class = TaskSerializer

Learn more How to create CRUD Operations using Django Viewsets.

Step 4 – Configure URLs: Create URL patterns for your API views:

from django.urls import path, include
from rest_framework.routers import DefaultRouter

router = DefaultRouter()
router.register(r'tasks', TaskViewSet)

urlpatterns = [
    path('', include(router.urls)),
]

Step 5 – Enable Basic Authentication: By default, DRF uses session-based authentication. To enable Basic Authentication, add it to your project’s settings:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.BasicAuthentication',
    ],
}

Step 6: Migrate and Run Server – Run migrations to create the necessary database tables:

python manage.py makemigrations
python manage.py migrate

Now, you can run your Django development server:

python manage.py runserver

Testing Basic Authentication

You can test Basic Authentication using tools like curl or Postman. Here’s an example using curl:

curl -X GET http://localhost:8000/tasks/ -H 'Authorization: Basic base64encoded(username:password)'

Replace base64encoded(username:password) with the actual Base64-encoded credentials.

For example, create a superuser using – python3 manage.py createsuperuser

Now you can go on this website ( https://www.base64encode.org/ ) and create Base64 String. Like i gave input admin:Password@123 and i got output as YWRtaW46UGFzc3dvcmRAMTIz

curl -X GET http://localhost:8000/tasks/ -H 'Authorization: Basic YWRtaW46UGFzc3dvcmRAMTIz'

Next: Now you can check our blog User Registration, Login, Logout API using Django Rest Framework

Conclusion

Basic Authentication in Django Rest Framework is a simple yet effective way to secure your API endpoints. However, it should be used with caution, and it’s crucial to transmit data over HTTPS to prevent unauthorized access to user credentials. As your project grows, you can explore more advanced authentication methods provided by DRF to meet specific security requirements.

Blogs You Might Like to Read!