docs
  • Overview
  • 🐍 PYTHON
    • Type Hints
    • PEP8 Style Guide for Python Code
    • 🏡Pipenv
    • Pathlib
  • 🕸Django
    • 🗄models
      • 🎯Best Practices
      • 🚦Django Signals
    • ⚙️ settings
    • DRF
      • Serializer
      • Authentication
      • Permissions
      • Viewsets
    • Testing
      • Faker and Factory Boy
    • 🧪Test Coverage
    • 💦Python-Decouple
    • Django Tips:
    • 💾Django ORM Queryset
    • Custom Exceptions
    • Celery
    • Resources
  • Deploy
    • 🚀Django Deployment
    • 🔒Setup SSL Certificate
  • 💾Database
    • MongoDB
  • 🛠️DevOps
    • 🖥Scripting
      • A First Script
      • Loops
      • Test
      • Variables
      • External programs
      • Functions
    • Command Line Shortcuts
    • Basic Linux Commands
    • 🎛Microservices
    • 🐳Docker
      • Docker Commands
      • Docker Compose
      • Django project
    • Kubernates
  • 📝Software IDE
    • EditorConfig
    • Linters
    • VsCode
Powered by GitBook
On this page
  • Authentication In Django Rest Framework
  • Authentication Flow in DRF
  • Default Authentication Classes provided by DRF
  • Globally configuring the authentication scheme in settings.py
  • How to override the global authentication classes in Views or Viewsets?
  • Setting Up Token Authentication in Django REST Framework

Was this helpful?

  1. 🕸Django
  2. DRF

Authentication

Authentication In DRF

Authentication In Django Rest Framework

Authentication means the process or action of verifying the identity of a user. REST framework provides a number of authentication schemes out of the box and also allows you to implement custom schemes. In Django REST framework does not restrict user access to the API resource. If we want to restrict the user access to the API then we have to use permissions and throttling classes

Authentication Flow in DRF

Whenever any request comes to Django Rest API view first it passed to method def dispatch(self, request, *args, **kwargs), it will take the list of all available authentication classes from the view attribute "authentication_classes" and it takes one class at a time from the "authentication_classes" and tries to authenticate the user with the authentication class if the class is able to authenticate the user then it will assign the property "user" to the "request" object. So, we can access the user like "request.user" to get the user in the view. If all of the authentication classes failed to authenticate the user then an "AnonymousUser" object is assigned to "request.user". If one of the authentication classes is able to authenticate the user then all other authentication classes will be skipped or will not be processed further.

Default Authentication Classes provided by DRF

By default, Django REST Framework provides two authentication classes. Below two classes are used to authenticate the user unless we override "authentication_classes" in the API view.

  1. rest_framework.authentication.BasicAuthentication

  2. rest_framework.authentication.SessionAuthentication

Globally configuring the authentication scheme in settings.py

We can override the default authentication classes provided by DRF in settings.py with the below configuration. We can also use our custom authentication classes and configure them like below.

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        # 'myapp.authentication.CustomAuthentication',
    )
}

How to override the global authentication classes in Views or Viewsets?

We can override the default authentication classes in views, But View must be a subclass of "APIView"

from rest_framework.authentication import BasicAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

class AuthExampleAPIView(APIView):
    authentication_classes = (BasicAuthentication, )

    def get(self, request, format=None):
        content = {
            'user': str(request.user)
        }
        return Response(content)

Setting Up Token Authentication in Django REST Framework

In addition to "BasicAuthentication", "SessionAuthentication" DRF also provides another authentication scheme called TokenAuthenticaction. To use token-based authentication in Dango REST Framework we need to do the following configurations.

# settings.py

INSTALLED_APPS = (
    'rest_framework',
    'rest_framework.authtoken',
    'myapp',
)

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
    )
}

# urls.py

from rest_framework.authtoken.views import ObtainAuthToken
from . import views
urlpatterns = [
    path('api/protected/', views.ProtectedAPIView.as_view(), name='protected'),
    path('api/token-auth/', ObtainAuthToken, name='auth_token'),
]

# views.py

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated

class ProtectedAPIView(APIView):
    permission_classes = (IsAuthenticated,)

    def get(self, request):
        data = {'message': 'I am proteted'}
        return Response(data)

How to get auth token?

import requests
params = {"username": "admin", "password": "secret"}
headers = {"content-type": "application/json"}
r = requests.post("https://localhost:8000/api/token-auth/", params, headers)
print(r.json())
# Output: {"token": "9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b"}

How to use obtained auth token?

import requests
headers = {"Authorization": "Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b", "content-type": "application/json"}
r = requests.get("https://localhost:8000/api/protected/", headers=headers)
print(r.json())
# Output: {"message": "I am protected"}

PreviousSerializerNextPermissions

Last updated 3 years ago

Was this helpful?