3

I have a backend API, it's in django and deployed on Google Endpoint. I have a post request that insert data to my DB.

I created a script to use this endpoint but I got this error:

{"detail":"CSRF Failed: Referer checking failed - no Referer."}

Regarding over posts I added the crsf_exempt decorator to my class but it did not change.
I try to add the decorator two ways:

class AddUser(APIView):
    """ Create user and company from csv """

    @method_decorator(csrf_exempt)
    def post(self, request):


@method_decorator(csrf_exempt, name='dispatch')
class AddUser(APIView):
    """ Create user and company from csv """

    def post(self, request):

But both failed.

This is how I contact my endpoint:

resp = requests.request(
    method, url,
    headers={'Authorization': 'Bearer {}'.format(
        open_id_connect_token)}, **kwargs)

Any ideas ? Thanks


EDIT

So I tried to add authentication classes to my views but it appears to be a bad idea. This is being real trouble for me.

I tried to get the csrftoken doing like this:

        client = requests.session()
        # Retrieve the CSRF token first
        client.get(url)  # sets cookie
        print(client.cookies)
        if 'csrftoken' in client.cookies:
            # Django 1.6 and up
            csrftoken = client.cookies['csrftoken']
        else:
            # older versions
            csrftoken = client.cookies

Thing is, I am using IAP to protect my API and I do not have any csrftoken cookie but I do have a something looking like this:

<RequestsCookieJar[<Cookie GCP_IAP_XSRF_NONCE_Q0sNuY-M83380ypJogZscg=1 for ...

How can I use this to make post request to my API ?

Kimor
  • 470
  • 3
  • 13

2 Answers2

2

So this happened to me because I did not set any authentication_classes to my generic view.
When this option is not set Django automatically use the SessionBackend, which need the csrf token.
I fixed it by adding this to my view: authentication_classes = [ModelBackend, GoogleOAuth2]

Sicco
  • 5,979
  • 4
  • 43
  • 59
Kimor
  • 470
  • 3
  • 13
0

@Kimor - Can you try doing this in your urls.py

 from django.views.decorators.csrf import csrf_exempt

url('^test/$', csrf_exempt(views.TestView.as_view())),

The get and post methods defined on the APIView class just tell DRF how the actual view should behave, but the view method that the Django router expects is not actually instantiated until you call TestView.as_view().

  • source

Django REST Framework CSRF Failed: CSRF cookie not set

SDRJ
  • 492
  • 2
  • 11
  • 1
    I have two endpoints and I did this on my path: path('my-path', csrf_exempt(AddUser.as_view()), name='my-path'), But the error is still happening – Kimor Feb 16 '21 at 15:54