简体   繁体   中英

Django Post 403 forbidden CSRF

I have a simple Django webhook that keeps returning a 403 forbidden despite I have marked it with csrf_exempt .

Here is the relevant code:

urls.py

 ...
 url(r'^mail/$', MailView.as_view(), name="mail"),
 ...

view.py

class MailView(View):
    @csrf_exempt
    def dispatch(self, *args, **kwargs):
        return super(MailTrackingView, self).dispatch(*args, **kwargs)

    def post(self, request, *args, **kwargs):
        return HttpResponse(status=204)

When sending data to this endpoint, Django gives a

Forbidden (CSRF cookie not set.): /mail/

What else do I have to set so the CSRF validation is not performed?

Add { %csrf_token% } in your form in the template.

And declare:

CSRF_COOKIE_SECURE = True

https://docs.djangoproject.com/en/2.0/ref/settings/#csrf-cookie-secure

I believe you have to wrap it inside method_decorator Try

class MailView(View):
    @method_decorator(csrf_exempt))        
    def dispatch(self, *args, **kwargs):
        return super(MailTrackingView, self).dispatch(*args, **kwargs)

You cal also do:

@method_decorator(csrf_exempt, name='dispatch')
class MailView(View):

Update

Do you have CSRF_USE_SESSIONS set to True?

Here's the code I used to test it and it works as expected; if the decorator is commented out, I get a 403 CSRF failure, if it is left then my post succeeds.

View File

class MyView(View):

    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(MyView, self).dispatch(*args, **kwargs)

    def post(self, request, *args, **kwargs):
        return HttpResponse(status=204)

    def get(self, request, *args, **kwargs):
        form = """
        Authenticated: {}
        <form method="post">
            <label for="your_name">Your name: </label>
            <input id="your_name" type="text" name="your_name">
            <input type="submit" value="OK">
        </form>
        """.format(request.user.is_authenticated())
        return HttpResponse(form)

URLs File

    url(r'^test/', views.MyView.as_view()),

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM