I'm using a django-oneall to allow social login session authentication on my site. While it isn't one of the suggested auth providers for django-rest-framework, rest_framework.authentication.SessionAuthentication
uses django's default session authentication. so I thought it should be fairly simple to integrate.
On the permissions side, ultimately I'll use IsAdmin
, but for development purposes, I just had it set to IsAuthenticated
. When that returning 403s, I relaxed the permissions to AllowAny
, but still no dice. Here's my rest framework config:
settings.py
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.AllowAny',
# 'rest_framework.permissions.IsAuthenticated',
# 'rest_framework.permissions.IsAdminUser',
),
'PAGE_SIZE': 100,
'DEFAULT_FILTER_BACKENDS': (
'rest_framework.filters.DjangoFilterBackend',
),
}
EDIT:
I got this working based on the answer below. It turns out that rest_framework
expects both the csrftoken
cookie and a a X-CSRFToken
Header of the same value, I setup my front-end code to send that header for all ajax requests and everything worked fine.
For completeness sake, there is one more circumstance under which DRF returns code 403: if you forget to add
as_view()
to the view declaration in your urls.py file. Just happened to me, and I spent hours until I found where the issue was, so maybe this addition can save some time for someone.Just for anyone that might find the same problem. If you are using viewsets without routers like:
Django Rest framework will return 403 unless you define permission_classes at a class level:
Hope it helps!
Django REST Framework returns status code
403
under a couple of relevant circumstances:DEFAULT_PERMISSION_CLASSES
is('rest_framework.permissions.IsAuthenticated',)
.rest_framework.authentication.SessionAuthentication
and you've not included your CSRFToken in the requeset.I'm going to make a few demo requests against a test API to give an example of each to help you diagnose which issue you are having and show how to resolve it. I'll be using the
requests
library.The test API
I set up a very simple DRF API with a single model,
Life
, that contains a single field (answer
, with a default value of42
). Everything from here on out is pretty straight forward; I set up aModelSerializer
-LifeSerializer
, aModelViewSet
-LifeViewSet
, and aDefaultRouter
on the/life
URL route. I've configured DRF to require user's be authenticated to use the API and to useSessionAuthentication
.Hitting the API