Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework behind HTTP Basic Authentication

If my webservice (powered by Django Rest Framework, v2.3.8) is inside a location protected by Nginx's HTTP Basic Authentication, like so:

location / {
            auth_basic           "Restricted access";
            auth_basic_user_file /path/to/htpasswd;

            uwsgi_pass django;
            include /etc/uwsgi/config/uwsgi_params;
    }

Then, when a user authenticate and tries to access the API, the following response is obtained for all views:

{"detail": "Invalid username/password"}

Does Django Rest Framework pick up the HTTP Authorization header (meant for Nginx) even though the view requires no authentication? If so, how should I go about this?

Any help would be greatly appreciated.

like image 844
Ikalou Avatar asked Oct 30 '13 20:10

Ikalou


People also ask

How do you implement basic authentication in Django REST framework?

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.

Which authentication is best in Django REST framework?

And these are all provided by drf(django rest framework) and other than these like oauth, oauth2 based authentication are provided by the efforts of the community with help of other python packages. And they can be easily used in the production environment.

What is basic authentication in REST API?

Basic authentication is an HTTP-based authentication approach and is the simplest way to secure REST APIs. It uses a Base64 format to encode usernames and passwords, both of which are stored in the HTTP header.


1 Answers

By default, Django Rest Framework has two authentication classes, see here.

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

You can disable the rest framework authentication if you don't need it.

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': ()
}

Or you can remove only BasicAuthentication as it will work in your case.

REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
    'rest_framework.authentication.SessionAuthentication'
)}
like image 64
ottojiang Avatar answered Sep 21 '22 18:09

ottojiang