VOOZH about

URL: https://www.geeksforgeeks.org/python/basic-authentication-django-rest-framework/

⇱ Basic Authentication in Django REST Framework - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Basic Authentication in Django REST Framework

Last Updated : 9 Apr, 2026

Authentication is a mechanism that provides access control based on the credentials associated with incoming requests. Django REST Framework (DRF) offers several authentication schemes. Basic Authentication verifies users using their username and password and is generally suitable for testing purposes.

When a request is authenticated using Basic Authentication:

  • request.user contains a Django User instance.
  • request.auth is None.

If authentication fails:

  • request.user is an instance of AnonymousUser.
  • request.auth is None.

Setting the authentication scheme globally

1. Global Configuration

To apply Basic Authentication across all views, set it as the default authentication class in settings.py.

2. Per-View Configuration

Function-Based Views: For function-based views, use @authentication_classes and @permission_classes decorators

Class-Based Views: For class-based views, set authentication and permission classes in APIView

The IsAuthenticated permission allows access only to authenticated users. By default, DRF uses AllowAny, which permits unrestricted access. 

Applying Basic Authentication to a RESTful API

To enforce Basic Authentication globally for your API, add the following in settings.py.

Then, set IsAuthenticated permission for API views:

Testing the API

Retrieving Data Without Credentials

Using HTTP:

http :8000/robot/

Output: The server returns 401 Unauthorized because authentication credentials were not provided.

👁 Image

Retrieving Data With Credentials

Create a superuser and provide credentials.

http -a "admin":"admin@123" :8000/robot/

Output: List of robots retrieved successfully

👁 Image

Creating a New Entry

http -a "admin":"admin@123" POST :8000/robot/ name="SR-3iA" robot_category="SCARA Robots" currency="USD" price=25000 manufacturer="Fanuc" manufacturing_date="2020-05-10 00:00:00+00:00"

Output: Robot entry created successfully

👁 Image

Production Considerations

  • Always use HTTPS when using Basic Authentication to prevent credentials from being exposed.
  • For deployments using Apache with mod_wsgi, set WSGIPassAuthorization On to ensure headers are passed correctly.
Comment
Article Tags: