146๐
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'
),
}
219๐
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
.
- [Django]-Has Django served an excess of 100k daily visits?
- [Django]-Is this the right way to do dependency injection in Django?
- [Django]-Django: Why do some model fields clash with each other?
45๐
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
}
- [Django]-Backwards migration with Django South
- [Django]-Get user profile in django
- [Django]-Django count RawQuerySet
25๐
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:
-
Make sure you have
'rest_framework.authtoken'
inINSTALLED_APPS
in yoursettings.py
. -
Make sure you have this somewhere in
settings.py
:REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', # ... ), # ... }
-
Make sure you have the correct token for the user who is logged in.
Basically, you need to do aPOST
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/
-
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,) # ...
-
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"
- [Django]-How to recursively query in django efficiently?
- [Django]-Get object by field other than primary key
- [Django]-MySQL "incorrect string value" error when save unicode string in Django
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)
- [Django]-Class has no objects member
- [Django]-How can I check the size of a collection within a Django template?
- [Django]-Has Django served an excess of 100k daily visits?
17๐
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
- [Django]-Django: Error: You don't have permission to access that port
- [Django]-Group by Foreign Key and show related items โ Django
- [Django]-Getting the SQL from a Django QuerySet
- [Django]-Django F() division โ How to avoid rounding off
- [Django]-Is it bad to have my virtualenv directory inside my git repository?
- [Django]-Django REST Framework: adding additional field to ModelSerializer
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',
)
}
- [Django]-Troubleshooting Site Slowness on a Nginx + Gunicorn + Django Stack
- [Django]-Altering one query parameter in a url (Django)
- [Django]-What is more efficient .objects.filter().exists() or get() wrapped on a try
6๐
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',
)
...
..
}
- [Django]-Django gives Bad Request (400) when DEBUG = False
- [Django]-How to query Case-insensitive data in Django ORM?
- [Django]-Django dump data for a single model?
4๐
Adding SessionAuthentication
in settings.py
will do the job
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
),
}
- [Django]-How do you dynamically hide form fields in Django?
- [Django]-Switching to PostgreSQL fails loading datadump
- [Django]-RuntimeWarning: DateTimeField received a naive datetime
2๐
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
- [Django]-Django aggregate or annotate
- [Django]-Error when using django.template
- [Django]-Django models: default value for column
2๐
In my case TokenAuthentication was missing
@authentication_classes([SessionAuthentication, BasicAuthentication])
I changed it to below and it worked
@authentication_classes([SessionAuthentication, BasicAuthentication, TokenAuthentication])
- [Django]-What's the difference between select_related and prefetch_related in Django ORM?
- [Django]-Django fix Admin plural
- [Django]-How to query as GROUP BY in Django?
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
- [Django]-How to check Django version
- [Django]-Gunicorn Connection in Use: ('0.0.0.0', 5000)
- [Django]-Django storages aws s3 delete file from model record
1๐
If you are using authentication_classes
then you should have is_active
as True
in User
model, which might be False
by default.
- [Django]-CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False
- [Django]-Can I access constants in settings.py from templates in Django?
- [Django]-Filtering using viewsets in django rest framework
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).
- [Django]-What is a "django backend"?
- [Django]-Django REST Framework : "This field is required." with required=False and unique_together
- [Django]-Is it bad to have my virtualenv directory inside my git repository?
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.
- [Django]-No handlers could be found for logger
- [Django]-Find object in list that has attribute equal to some value (that meets any condition)
- [Django]-How to filter objects for count annotation in Django?
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.
- [Django]-Effects of changing Django's SECRET_KEY
- [Django]-How about having a SingletonModel in Django?
- [Django]-Setting DEBUG = False causes 500 Error
0๐
I had strange issue for this error.
I was getting Token correctly and was passing Authorization token correctly in Postman and was still getting this error
{"detail": "Authentication credentials were not provided."}
I searched it on internet and check many SO questions. But nothing worked.
Then i closed Postman application and restart it again then it worked. I had no idea why Postman was behaving like that.
Thankfully problem is solved ๐
- [Django]-Effects of changing Django's SECRET_KEY
- [Django]-Django, Models & Forms: replace "This field is required" message
- [Django]-Django south migration โ Adding FULLTEXT indexes
0๐
I had the same issue with postman and django backend. I used to use Bearer token
but it started failing, I had to manually add the Authorization
Header on Headers
while prepending it with Token
ie Token token
- [Django]-Django model "doesn't declare an explicit app_label"
- [Django]-How to pass information using an HTTP redirect (in Django)
- [Django]-Default value for user ForeignKey with Django admin
0๐
Iโd also add that for those looking to implement Token only authentication. Ensure that your ViewSetโs have the "authentication_classes" attribute.
For example:
from rest_framework.authentication import TokenAuthentication
class TaskViewSet(viewsets.ModelViewSet):
"""
Tasks for the current user. This endpoint allows tasks to be viewed or edited.
"""
queryset = Task.objects.all().order_by('-created_at')
serializer_class = TaskSerializer
authentication_classes = [TokenAuthentication]
permission_classes = [permissions.IsAuthenticated]
This will bypass the requirement for the users Username and Password to be required in the sessions request.
- [Django]-Adding css class to field on validation error in django
- [Django]-Django Generic Views using decorator login_required
- [Django]-Checking for empty queryset in Django