swsnu / swppfall2019

31 stars 23 forks source link

How to Solve "CSRF cookie not set" Error in Deployment Environment #212

Open kyunggeunlee opened 4 years ago

kyunggeunlee commented 4 years ago

In the last practice session, we teached you how to deploy your projects using Azure VM, but it seems that many teams are having problem in managing CSRF tokens when deployed. The reason why you get "CSRF cookie not set" error is because you have sent a POST, DELETE, or PUT request when you don't have CSRF token in your cookies. This won't happen again once you get the CSRF token before these requests.

To get CSRF token, you have to send a GET request to Django so that a view function decorated by @ensure_csrf_cookie decorator returns an HTTP response (see skeleton code of HW3).

For example, one naive solution is to GET request in index.js to get CSRF token. Or, you can also make a wrapper class of axios and check whether you have the CSRF token in your cookies before you send every POST, DELETE, and PUT request.


지난번 실습 수업 때 deploy 하는 방법을 알려드렸는데, 이 때 CSRF token 문제가 발생하는 팀들이 많은 것 같습니다. Django에서 "CSRF cookie not set" 라는 오류가 발생하는 이유는 아직 CSRF token 을 발급받은 적이 없는 상태에서 POST, DELETE, PUT 등의 리퀘스트를 보냈기 때문입니다. CSRF token을 한번 발급받고 나면 그 뒤로는 이러한 문제가 발생하지 않습니다.

CSRF token을 발급받으려면 @ensure_csrf_cookie 데코레이터로 감싼 view function이 실행되도록 (HW3 skeleton 참고) GET 리퀘스트를 보내시면 됩니다.

예를 들어 naive하게는 index.js 에서 CSRF token을 받아오도록 GET 리퀘스트를 보낼 수도 있고, 또는 axios 를 감싸는 wrapper class를 하나 만들어서 POST, DELETE, PUT 등의 리퀘스트를 보낼 때마다 CSRF cookie가 존재하는지를 확인하고 보내는 방법도 있겠습니다.

import Cookie from 'js-cookie';

// Check CSRF cookie before POST, DELETE, and PUT request.
if (Cookie.get().csrftoken === undefined) {
    axios.get('/api/token/')
         .then(res => { axios.post(...); });
}