Getting Django, VUE, CORS and CSRF working with a real world example

后端 未结 2 953
离开以前
离开以前 2021-01-18 07:15

I\'m really stuck. Here\'s what I\'m trying to do.

  1. KEEP CSRF On. - please don\'t tell me to turn it off.
  2. I have an API app run by Django and Django R
2条回答
  •  误落风尘
    2021-01-18 07:21

    By far the easiest way to resolve this is to serve everything from the same domain. You can have your CDN or proxy direct /api calls to one server and the rest to the frontend server. This way there is no need to worry about CORS at all.

    To get this working, I think you're just missing withCredentials = true in AXIOS configuration. Django requires the CSRF cookie to be sent and cookies are not sent over cross origin requests when withCredentials is not set.

    axios.interceptors.request.use(function (config) {
      config.withCredentials = true
      return config
    })
    

    Another setting that might be missing is Djano's SESSION_COOKIE_DOMAIN. You should set it like this:

    SESSION_COOKIE_DOMAIN=".mywebsite.com"
    

    That first dot is important because it tells Django and then the web browser to use the cookie for *.mywebsite.com including api.mywebsite.com.

    If it all still fails, I suggest setting a breakpoint on Django's CSRF middleware to see what's missing to make it work.

提交回复
热议问题