Basic Authentication - Django REST Framework - GeeksforGeeks

14 Sep, 2021
Authentication is a mechanism that provides access control based on the credentials associated with incoming requests. Django REST Framework provides several authentication schemes. In this section, let’s look at the Basic Authentication in Django rest framework, i.e., authenticated against a user’s username and password.
Basic Authentication in Django REST Framework uses HTTP Basic Authentication. It is generally appropriate for testing. The REST framework will attempt to authenticate the Basic Authentication class and set the returned values to request.user and request.auth. If successfully authenticated, BasicAuthentication provides the following credentials.
request.user will be a Django User instance.
request.auth will be None.
if not, the value of request.user will be set to as an instance of django.contrib.auth.models.AnonymousUser, and request.auth will be set to None. To make of BasicAuthentication scheme, we need to set it to the default authentication scheme. You can either set it globally or you can set the authentication scheme on a per-view basis.
You can set the authentication globally by using the DEFAULT_AUTHENTICATION_CLASSES setting.
Python3
REST_FRAMEWORK = {    'DEFAULT_AUTHENTICATION_CLASSES': [        'rest_framework.authentication.BasicAuthentication',    ]}
Setting the authentication scheme on a per-view basis differs in function-based views and class-based views.
We can make use of @authentication_classes and @permission_classes decorators to set the authentication scheme in function-based views that use @api_view decorator. The sample code is as follows:
Python3
@api_view(['GET'])@authentication_classes([BasicAuthentication])@permission_classes([IsAuthenticated])def function_based_view(request, format=None):    content = {                # `django.contrib.auth.User` instance        'user': str(request.user),                # None        'auth': str(request.auth),    }    return Response(content)
By using the APIView class, we can set the authentication scheme in class-based views. The sample code is as follows:
Python3
from rest_framework.authentication import SessionAuthentication, BasicAuthenticationfrom rest_framework.permissions import IsAuthenticatedfrom rest_framework.response import Responsefrom rest_framework.views import APIView  class ClassBasedView(APIView):    authentication_classes = [BasicAuthentication]    permission_classes = [IsAuthenticated]      def get(self, request, format=None):        content = {                        # `django.contrib.auth.User` instance            'user': str(request.user),                        # None            'auth': str(request.auth),        }        return Response(content)
Note: Here, we will use the simplest style of permission that allows access to any authenticated user, and deny access to any unauthenticated user. This corresponds to the ‘IsAuthenticated’ class in REST framework. If not set to ‘IsAuthenticated’ class, it uses the default class ‘AllowAny’, which allows unrestricted access. 
Let’s set the BasicAuthentication scheme globally. You can open the settings.py file of our restful web service and add the below code.
Python3
REST_FRAMEWORK = {    'DEFAULT_AUTHENTICATION_CLASSES'        'rest_framework.authentication.BasicAuthentication',        )}
Note: You can refer The Browsable API section for Models, Serializers, and Views of Project used in the article
Here we set the BasicAuthentication scheme globally, so we don’t need to set it for each view.  But we need to set the permission class since, by default, the permission class is set to AllowAny, which allows unrestricted access. To make use IsAuthenticated class we need to import it from rest_framework.permissions.
from rest_framework.permissions import IsAuthenticated
Now, let’s set the permission class to ‘IsAuthenticated’ for RobotDetail and RobotList class. The code is as follows:
Python3
class RobotDetail(generics.RetrieveUpdateDestroyAPIView):    permission_classes = [IsAuthenticated]    queryset = Robot.objects.all()    serializer_class = RobotSerializer    name = 'robot-detail'    class RobotList(generics.ListCreateAPIView):    permission_classes = [IsAuthenticated]    queryset = Robot.objects.all()    serializer_class = RobotSerializer    name = 'robot-list'
Let’s try to retrieve robots without providing any credentials. The HTTPie command is
http :8000/robot/
Output
Now we will create a superuser and provide the credentials to retrieve robots. You can follow How to create superuser in Django? to create a superuser.
Let’s try the HTTPie command with credentials to retrieve the robots.
http -a “admin”:”admin@123′′ :8000/robot/
Output
Let’s try an HTTPie command that creates a new robot 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
Note: If you use BasicAuthentication in production, you should ensure your API is available only for HTTPS and always re-request the credentials. If you are deploying to Apache using mod_wsgi, you need to explicitly configure mod_wsgi to pass the required headers through to the application by setting the WSGIPassAuthorization to ‘On’.
Django-REST
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Pandas dataframe.groupby()
Create a directory in Python
Defaultdict in Python
Python | Get unique values from a list