How to make a POST simple JSON using Django REST Framework? CSRF token missing or incorrect

前端 未结 8 2111
清酒与你
清酒与你 2020-12-04 15:50

Would appreciate someone showing me how to make a simple POST request using JSON with Django REST framework. I do not see any examples of this in the tutorial anywhere?

8条回答
  •  渐次进展
    2020-12-04 15:56

    To give an update on current status, and sum up a few answers:

    AJAX requests that are made within the same context as the API they are interacting with will typically use SessionAuthentication. This ensures that once a user has logged in, any AJAX requests made can be authenticated using the same session-based authentication that is used for the rest of the website.

    AJAX requests that are made on a different site from the API they are communicating with will typically need to use a non-session-based authentication scheme, such as TokenAuthentication.

    Therefore, answers recommending to replace SessionAuthentication with TokenAuthentication may solve the issue, but are not necessarily totally correct.

    To guard against these type of attacks, you need to do two things:

    1. Ensure that the 'safe' HTTP operations, such as GET, HEAD and OPTIONS cannot be used to alter any server-side state.

    2. Ensure that any 'unsafe' HTTP operations, such as POST, PUT, PATCH and DELETE, always require a valid CSRF token. If you're using SessionAuthentication you'll need to include valid CSRF tokens for any POST, PUT, PATCH or DELETE operations.

    In order to make AJAX requests, you need to include CSRF token in the HTTP header, as described in the Django documentation.

    Therefore, it is important that csrf is included in header, as for instance this answer suggests.

    Reference: Working with AJAX, CSRF & CORS, Django REST framework documentation.

提交回复
热议问题