Home > Enterprise >  Django REST Framework BasicAuthentication is not applied as default authentication class
Django REST Framework BasicAuthentication is not applied as default authentication class

Time:10-05

I have a Django REST Framework project and I added

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.BasicAuthentication',
    ]
}

to settings.py and I expect BasicAuthentication is applied to all pages as default but still it does not require any authentication to display the content. that is weird. Do I have to do something I did not do?
urls.py:

urlpatterns = [
    path('admin/', admin.site.urls),
    path('student/', include('blogapp.urls')),
    path('api/', include('api.urls')),
    path('api-auth/', include('rest_framework.urls')),
]

setting.py:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'blogapp',
]

blog_app/urls:

urlpatterns = [
    path('', StudentView.as_view()),
]

views.py:

class StudentView(generics.ListCreateAPIView):
    queryset = Student.objects.all()
    serializer_class = StudentSerializer

UPDATE 1:

Also per-view authentications not work!

UPDATE 2:

This is my project source code.

CodePudding user response:

Authentication is not the same as permission. You'll also need to add a default permission class if you require all users to be authenticated (using one of the authentication methods you wish to use):

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.BasicAuthentication',
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
    ],
}

Also, make sure you're testing the right view (/api/list/). Your project (as you linked) has two StudentViews, one of which is a DRF view, the other (/student/) isn't. The latter will not be aware of DRF configuration.

  • Related