title: Getting Django, VUE, CORS and CSRF working with a real world example
body: <p>I'm really stuck. Here's what I'm trying to do.</p>
  
  <ol>
  <li>KEEP CSRF On.  - please don't tell me to turn it off.</li>
  <li>I have an API app run by Django and Django Rest Framework</li>
  <li>I have a frontend app run by Vue</li>
  <li>I have installed django-cors-headers to manage CORS</li>
  </ol>
  
  <p>Everything works great localy. As soon as I move it to production, I start getting CSRF errors. Here's how everything works.</p>
  
  <p>I've seen answers all over that have said everything from turning off CSRF to allowing all for all the things. I want to do this right and not just shut things off and open everything up and end up with a security hole.</p>
  
  <p>So, here's what I have.</p>
  
  <p>Installed:
  django-cors-headers
  django-rest-framework
  drf-nested-routers
  ... and others</p>
  
  <p>I have the api running at api.websitename.com and the Vue.js app is running at websitename.com.</p>
  
  <p>GET requests work great.
  OPTION requests seem to work.</p>
  
  <p>Any risky request does not work.</p>
  
  <p>For my CORS I have <code>'corsheaders.middleware.CorsMiddleware',</code> installed before my other <code>MIDDLEWARE</code>.</p>
  
  <p>Then my CORS settings are:</p>
  
  <pre><code>CORS_ALLOW_CREDENTIALS = True
  CORS_ORIGIN_WHITELIST = (
      '*.websitename.com',
  )
  </code></pre>
  
  <p>And my CSRF settings are:</p>
  
  <pre><code>CSRF_TRUSTED_ORIGINS = [
      "api.websitename.com",
  ]
  </code></pre>
  
  <p>No matter how I play with these, I end up with a CSRF token error.</p>
  
  <p>I've tried the approach of doing something like this in my Vue App.vue file:</p>
  
  <pre><code>mounted () {
    this.getCSRFToken()
  },
  methods: {
    getCSRFToken () {
      return axios.get('token/').then(response =&gt; {
        axios.defaults.headers.common['x-csrftoken'] = Cookies.get('csrftoken')
      }).catch(error =&gt; {
        return Promise.reject(error.response.data)
      })
    }
  }
  </code></pre>
  
  <p>The idea being that I get a CSRF token as soon as the APP loads in the browser. But even with that, I'm getting failed CSRF token errors when the app tries to do anything except a GET or OPTION.</p>
  
  <p>Here's the view that returns the token incase youre curios:</p>
  
  <pre><code>class CSRFTokenView(APIView):
      permission_classes = (permissions.AllowAny,)
  
      @method_decorator(ensure_csrf_cookie)
      def get(self, request):
          return HttpResponse()
  </code></pre>
  
  <p>I realize I might be mixing problems here, but any suggestions that could help me trouble shoot this are welcome.</p>