Search code examples
pythondjangodjango-rest-frameworkdjango-authentication

Custom rest_framework authentication not getting called


I am using djangorestframework 3.9.2

I have following setting for rest_framework

....
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'my_project.middlewares.authentication.CentralAuthentication',
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'my_project.middlewares.authorization.CentralAuthorization'
    ],
}
....

And my directory structure is this

├── app1/
└── my_project
    ├── __init__.py
    ├── middlewares
    │   ├── __init__.py
    │   ├── authentication.py
    │   └── authorization.py
    ├── settings
    │   ├── __init__.py
    │   ├── commons.py
    │   ├── development.py
    │   └── logger.py
    ├── urls.py
└── wsgi.py

My authentication script is not getting call whenever I access my URL.

Is there something I am missing over here?


Solution

  • These permission classes or authentication classes are not middlewares and it will not get executed automatically. These classes are works only with DRF views

    So, define a DRF view and wire-up the view in your urls.py module

    from rest_framework.views import APIView
    from rest_framework.response import Response
    
    
    class FooAPI(APIView):
        def get(self, request, *args, **kwargs):
            return Response({'message': 'success'})
    
    
    urlpatterns = [
        path('foo/', FooAPI.as_view(), name='foo-api'),
    
    ]
    

    During the execution of this FooAPI class, the DRF will call the default permission_classes and authentication_classes