154

I'm developing an API using Django Rest Framework. I'm trying to list or create an "Order" object, but when i'm trying to access the console gives me this error:

{"detail": "Authentication credentials were not provided."}

Views:

from django.shortcuts import render
from rest_framework import viewsets
from django.contrib.auth.models import User
from rest_framework.renderers import JSONRenderer, YAMLRenderer
from rest_framework.response import Response
from rest_framework.views import APIView
from order.models import *
from API.serializers import *
from rest_framework.permissions import IsAuthenticated

class OrderViewSet(viewsets.ModelViewSet):
    model = Order
    serializer_class = OrderSerializer
    permission_classes = (IsAuthenticated,)

Serializer:

class OrderSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = Order
        fields = ('field1', 'field2')

And my URLs:

# -*- coding: utf-8 -*-
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.contrib import admin
from django.utils.functional import curry
from django.views.defaults import *
from rest_framework import routers
from API.views import *

admin.autodiscover()

handler500 = "web.views.server_error"
handler404 = "web.views.page_not_found_error"

router = routers.DefaultRouter()
router.register(r'orders', OrdersViewSet)

urlpatterns = patterns('',
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
    url(r'^api-token-auth/', 'rest_framework.authtoken.views.obtain_auth_token'),
    url(r'^api/', include(router.urls)),
)

And then I'm using this command in the console:

curl -X GET http://127.0.0.1:8000/api/orders/ -H 'Authorization: Token 12383dcb52d627eabd39e7e88501e96a2sadc55'

And the error say:

{"detail": "Authentication credentials were not provided."}
4
  • 8
    Try this: curl -H "Authorization: Token 12383dcb52d627eabd39e7e88501e96a2sadc55" http://127.0.0.1:8000/api/orders/
    – cor
    Nov 13, 2014 at 10:33
  • 1
    Same error. Authentication credentials were not provided Nov 13, 2014 at 10:35
  • In my case this happened due to a teammate switching the user to inactive mode.
    – Brock
    Dec 11, 2015 at 21:51
  • Try to read Authentication first.
    – endless
    Feb 26, 2018 at 12:50

17 Answers 17

210

If you are running Django on Apache using mod_wsgi you have to add

WSGIPassAuthorization On

in your httpd.conf. Otherwise, the authorization header will be stripped out by mod_wsgi.

8
  • 1
    In case if you are wondering where to write this, follow the link. stackoverflow.com/questions/49340534/… Apr 18, 2018 at 8:41
  • 3
    for ubuntu there seems no httpd.conf. so you have to add WSGIPassAuthorization On in /etc/apache2/apache2.conf
    – suhailvs
    Jun 25, 2018 at 1:19
  • I was confused by an issue where my requests from Postman were working from my localhost but not when sent to the live server. Your comment solved my issue.
    – RommelTJ
    Sep 10, 2019 at 14:30
  • Solved My problem, I was able to get data via api on my localhost, but when deployed on server over https:// it was giving me same error.
    – Mir Suhail
    Feb 4, 2020 at 11:42
  • Is this true only in production or for local development as well? May 10, 2020 at 5:15
142

Solved by adding "DEFAULT_AUTHENTICATION_CLASSES" to my settings.py

REST_FRAMEWORK = {
   'DEFAULT_AUTHENTICATION_CLASSES': (
       'rest_framework.authentication.TokenAuthentication',
   ),
   'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAdminUser'
   ),
}
3
  • Thought I did this, but I had added 'rest_framework.authentication.TokenAuthentication' to DEFAULT_PERMISSION_CLASSES instead of DEFAULT_AUTHENTICATION_CLASSES
    – netdigger
    Aug 8, 2016 at 8:18
  • 6
    Thanks for this solution! I don't understand however why I didn't get the "Authentication credentials were not provided." error when making the request with Postman, whereas I did get the error when my Angular client made requests. Both with the same token in the Authorization header... Mar 7, 2018 at 12:20
  • 3
    SessionAuthentication is enabled by default and works with the standard session cookies, so it's likely that your Angular (or other JS framework) application was working because of the default session authentication. Jul 2, 2020 at 22:57
44

This help me out without "DEFAULT_PERMISSION_CLASSES" in my settings.py

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ),
    'PAGE_SIZE': 10
}
4
  • 6
    The SessionAuthentication was what fixed it for me Apr 6, 2018 at 23:42
  • Fixed it for me too. Wonder why the Django tutorial on this doesn't mention it. See django-rest-framework.org/tutorial/quickstart .
    – Nick T
    May 17, 2020 at 7:42
  • 1
    has any one figured out why it behaves like this? session on a mobile device has to do nothing with having a jwt token in the header of the request !! I am surprised by this solution after 5 hours of digging.
    – decoder
    Feb 26, 2021 at 4:00
  • The SessionAuthentication works for me, too. Now I understand why my code didn't work.
    – kokserek
    Sep 7, 2022 at 10:52
24

Just for other people landing up here with same error, this issue can arise if your request.user is AnonymousUser and not the right user who is actually authorized to access the URL. You can see that by printing value of request.user . If it is indeed an anonymous user, these steps might help:

  1. Make sure you have 'rest_framework.authtoken' in INSTALLED_APPS in your settings.py.

  2. Make sure you have this somewhere in settings.py:

    REST_FRAMEWORK = {
    
        'DEFAULT_AUTHENTICATION_CLASSES': (
            'rest_framework.authentication.TokenAuthentication',
            # ...
        ),
    
        # ...
    }
    
  3. Make sure you have the correct token for the user who is logged in. If you do not have the token, learn how to get it here. Basically, you need to do a POST request to a view which gives you the token if you provide the correct username and password. Example:

    curl -X POST -d "user=Pepe&password=aaaa"  http://localhost:8000/
    
  4. Make sure the view which you are trying to access, has these:

    class some_fancy_example_view(ModelViewSet): 
    """
    not compulsary it has to be 'ModelViewSet' this can be anything like APIview etc, depending on your requirements.
    """
        permission_classes = (IsAuthenticated,) 
        authentication_classes = (TokenAuthentication,) 
        # ...
    
  5. Use curl now this way:

    curl -X (your_request_method) -H  "Authorization: Token <your_token>" <your_url>
    

Example:

    curl -X GET http://127.0.0.1:8001/expenses/  -H "Authorization: Token 9463b437afdd3f34b8ec66acda4b192a815a15a8"
2
  • How can one print request.user? It appears that the POST method of a class-based view is never getting processed. Where else can I try to print the user? May 10, 2020 at 5:19
  • user has to be authenticated to be able to being getting set in request object. Otherwise it just prints anonymous user. How are you authenticating your user ?
    – sherelock
    May 10, 2020 at 21:14
20

If you are playing around in the command line (using curl, or HTTPie etc) you can use BasicAuthentication to test/user your API

    REST_FRAMEWORK = {
        'DEFAULT_PERMISSION_CLASSES': [
            'rest_framework.permissions.IsAuthenticated',
        ],
        'DEFAULT_AUTHENTICATION_CLASSES': (
            'rest_framework.authentication.BasicAuthentication',  # enables simple command line authentication
            'rest_framework.authentication.SessionAuthentication',
            'rest_framework.authentication.TokenAuthentication',
        )
    }

You can then use curl

curl --user user:password -X POST http://example.com/path/ --data "some_field=some data"

or httpie (its easier on the eyes):

http -a user:password POST http://example.com/path/ some_field="some data"

or something else like Advanced Rest Client (ARC)

1
  • BasicAuthentication is not simple command line authentication
    – llazzaro
    May 13, 2021 at 1:07
15

For me, I had to prepend my Authorization header with "JWT" instead of "Bearer" or "Token" on Django DRF. Then it started working. eg -

Authorization: JWT asdflkj2ewmnsasdfmnwelfkjsdfghdfghdv.wlsfdkwefojdfgh

2
  • Same here. Using Next.JS with Django DRF as backend.
    – kenneho
    Sep 23, 2020 at 13:09
  • Agreed. Trying django with react for the first time and your answer helped me.
    – Rahul
    Nov 24, 2020 at 11:50
12

I too faced the same since I missed adding

authentication_classes = (TokenAuthentication)

in my API view class.

class ServiceList(generics.ListCreateAPIView):
    authentication_classes = (SessionAuthentication, BasicAuthentication, TokenAuthentication)
    queryset = Service.objects.all()
    serializer_class = ServiceSerializer
    permission_classes = (IsAdminOrReadOnly,)

In addition to the above, we need to explicitly tell Django about the Authentication in settings.py file.

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

I was having this problem with postman.Add this to the headers... enter image description here

3
  • 1
    In my case, I had not selected the checkbox... :) Thanks, this gave me the clue
    – Laxmikant
    Sep 21, 2020 at 14:19
  • I am using thunder client (extension for VS code) to check my API. The checkbox is authomatically checked when we add a new header of field or whatever. So this never came in my mind. But after seeing this answer, i unchecked the checkbox and then checked that again and that worked. Thanks..
    – Irfan wani
    Jun 20, 2021 at 9:32
  • 1
    I forgotten to add the "Token " prefix, careful guys
    – Ryan
    Mar 27, 2022 at 11:05
5

Try this, it worked for me.

In settings.py

SIMPLE_JWT = {
     ....
     ...
     # Use JWT 
     'AUTH_HEADER_TYPES': ('JWT',),
     # 'AUTH_HEADER_TYPES': ('Bearer',),
     ....
     ...
}

Add this too

REST_FRAMEWORK = {
    ....
    ...
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    )
    ...
    ..
}
1
  • 1
    thank you so much)) worked with only 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', Nov 29, 2022 at 19:49
4

Adding SessionAuthentication in settings.py will do the job

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

Since it is session Login so you need to provide you credentials so do 127.0.0:8000/admin admin and login later it will work fine

2
  • 2
    Sorry, but this question is already answered with more detail than yours... Mar 12, 2020 at 6:14
  • This is for the people who need quick solution Mar 12, 2020 at 9:06
1

If you are using authentication_classes then you should have is_active as True in User model, which might be False by default.

2
  • what are the authentication classes?
    – Sam
    Dec 4, 2020 at 14:24
  • 1
    How do we do this? Jun 13, 2021 at 16:37
1

Also make sure that the Authorization Token / API key is actually valid. The Authentication credentials were not provided. error message seems to be what's returned by the API if the key is invalid as well (I encountered this when I accidently used the wrong API key).

1

if anyone come here from Full Stack React & Django [5] - Django Token Authentication - Traversy Media So you need to something like this

accounts/api.py

from rest_framework import generics, permissions
from rest_framework.response import Response
from knox.models import AuthToken
from .serializers import LoginSerializer, RegisterSerializer, UserSerializer
from knox.auth import TokenAuthentication

# Register Api


class RegisterAPI(generics.GenericAPIView):
    serializer_class = RegisterSerializer

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.save()
        return Response({
            "user": UserSerializer(user, context=self.get_serializer_context()).data,
            "token": AuthToken.objects.create(user)[1]
        })

# Login Api


class LoginAPI(generics.GenericAPIView):
    serializer_class = LoginSerializer

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data
        return Response({
            "user": UserSerializer(user, context=self.get_serializer_context()).data,
            "token": AuthToken.objects.create(user)[1]
        })

# Get User Api


class UserAPI(generics.RetrieveAPIView):
    authentication_classes = (TokenAuthentication,)
    permission_classes = [
        permissions.IsAuthenticated,
    ]

    serializer_class = UserSerializer

    def get_object(self):
        return self.request.user
1

In my case TokenAuthentication was missing

@authentication_classes([SessionAuthentication, BasicAuthentication])

I changed it to below and it worked

@authentication_classes([SessionAuthentication, BasicAuthentication, TokenAuthentication])
0

In case you are using a CDN, check that the CDN doesn't remove the request header when if forwards the request to your server.

0

I added this in settings.py:

REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
    'rest_framework.authentication.TokenAuthentication',
    'rest_framework.authentication.SessionAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': [
    'rest_framework.permissions.IsAuthenticated',
],

}

and I created a superuser and created a token using:

python manage.py createsuperuser

and created a token using http://127.0.0.1:8000/admin/authtoken/tokenproxy/ and nothing else and it just worked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.