Django requires CSRF token in POST
request by default. to avoid CSRF tokens.
Don't use SessionAuthentication
as authentication class, coz, it will force you to add CSRF token.
If you still want to use SessionAuthentication
then You can use it overrideing
def enforce_csrf(self, request):
method
Try below this:
from rest_framework.authentication import SessionAuthentication
class CsrfExemptSessionAuthentication(SessionAuthentication):
def enforce_csrf(self, request):
pass
and use it in your views:
authentication_classes = (CsrfExemptSessionAuthentication ,TokenAuthentication)
If you want to use it globally, you can place it in your REST_FRAMEWORK settings.py file like this:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
'myapp.path-to-file.CsrfExemptSessionAuthentication'
],
}
Please make sure you add correct file path in the REST_FRAMEWORK settings
To authenticate with the token.
You must request like this:
curl -X GET http://127.0.0.1:8000/api/example/ -H 'Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b'
Also make sure you added this in your INSTALLED_APP:
INSTALLED_APPS = [
''''
'rest_framework',
'rest_framework.authtoken',
]
More details can be found here: https://www.django-rest-framework.org/api-guide/authentication/