Handling authentication

REST framework provides authentication classes to identify the user performing the request. If authentication is successful, the framework sets the authenticated User object in request.user. If no user is authenticated, an instance of Django's AnonymousUser is set instead.

REST framework provides the following authentication backends:

  • BasicAuthentication: This is HTTP basic authentication. The user and password are sent by the client in the Authorization HTTP header encoded with Base64. You can learn more about it at https://en.wikipedia.org/wiki/Basic_access_authentication.
  • TokenAuthentication: This is token-based authentication. A Token model is used to store user tokens. Users include the token in the Authorization HTTP header for authentication.
  • SessionAuthentication: This one uses Django's session backend for authentication. This backend is useful to perform authenticated AJAX requests to the API from your website's frontend.
  • RemoteUserAuthentication: This allows you to delegate authentication to your web server, which sets a REMOTE_USER environment variable.

You can build a custom authentication backend by subclassing the BaseAuthentication class provided by REST framework and overriding the authenticate() method.

You can set authentication on a per-view basis, or set it globally with the DEFAULT_AUTHENTICATION_CLASSES setting.

Authentication only identifies the user performing the request. It won't allow or deny access to views. You have to use permissions to restrict access to views.

You can find all the information about authentication at https://www.django-rest-framework.org/api-guide/authentication/.

Let's add BasicAuthentication to our view. Edit the api/views.py file of the courses application and add an authentication_classes attribute to CourseEnrollView as follows:

from rest_framework.authentication import BasicAuthentication

class CourseEnrollView(APIView):
authentication_classes = (BasicAuthentication,)
# ...

Users will be identified by the credentials set in the Authorization header of the HTTP request.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset