1

I am into a weird situation I am login into site and try to submit form if I use permission_classes = [AllowAny] or isAuthenticate classes I get error CSRF Failed: CSRF token missing or incorrect

And in following scenario it gives a popup to enter password and user name . My full class is like

class AddReview(APIView):
    serializer_class = ReviewSerializer
    authentication_classes = (BasicAuthentication,)
    def post(self, request):  
        rest = request.POST.get('restaurant')
        dish = request.POST.get('dish')

And my settings.py is

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',

    ),
}

I just want to submit a post custom form to submit data. Any help or suggestion to make question good would be highly appericiated.

Update

I am able to submit form by using this

class SessionAuthentication(SessionAuthentication):
    def enforce_csrf(self, request):
        return

But why I have to enforce it ? What I am doing wrong ?

gamer
  • 603
  • 4
  • 20

1 Answers1

0

Ideally, you website form should have a csrf token and that should also be sent to server. Maybe something like :

<form method="post">{% csrf_token %}</form>
  1. The CSRF middleware is activated by default in the MIDDLEWARE setting.
  2. If you want to disable CSRF protection just a few views use csrf_exempt() decorator

References

https://docs.djangoproject.com/en/2.2/ref/csrf/#csrf-protection-should-be-disabled-for-just-a-few-views

https://docs.djangoproject.com/en/2.2/ref/csrf/

Umair Mohammad
  • 4,489
  • 2
  • 20
  • 34
  • Everything is same as you mentioned . I have included token. When I submit form I get a anonymous user If I dont include " authentication_classes = (BasicAuthentication,) " before function of post In this case I get a authentication popup in chrome. – gamer Sep 16 '19 at 20:11
  • What is the response code and headers ? https://www.django-rest-framework.org/api-guide/authentication/#unauthorized-and-forbidden-responses – Umair Mohammad Sep 16 '19 at 20:16
  • removed authentication classes from view then I am getting this = >> HTTP 403 Forbidden Allow: POST, OPTIONS Content-Type: application/json Vary: Accept { "detail": "CSRF Failed: CSRF token missing or incorrect." } – gamer Sep 16 '19 at 20:18
  • if I add authentication_classes = (BasicAuthentication,) it asks username and password in popup – gamer Sep 16 '19 at 20:19
  • I think BasicAuthentication is for API, for web pages session should work - or you'll need to explore more on this – Umair Mohammad Sep 17 '19 at 04:54