I'm really stuck. Here's what I'm trying to do.
- KEEP CSRF On. - please don't tell me to turn it off.
- I have an API app run by Django and Django Rest Framework
- I have a frontend app run by Vue
- I have installed django-cors-headers to manage CORS
Everything works great localy. As soon as I move it to production, I start getting CSRF errors. Here's how everything works.
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.
So, here's what I have.
Installed: django-cors-headers django-rest-framework drf-nested-routers ... and others
I have the api running at api.websitename.com and the Vue.js app is running at websitename.com.
GET requests work great. OPTION requests seem to work.
Any risky request does not work.
For my CORS I have 'corsheaders.middleware.CorsMiddleware',
installed before my other MIDDLEWARE
.
Then my CORS settings are:
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_WHITELIST = (
'*.websitename.com',
)
And my CSRF settings are:
CSRF_TRUSTED_ORIGINS = [
"api.websitename.com",
]
No matter how I play with these, I end up with a CSRF token error.
I've tried the approach of doing something like this in my Vue App.vue file:
mounted () {
this.getCSRFToken()
},
methods: {
getCSRFToken () {
return axios.get('token/').then(response => {
axios.defaults.headers.common['x-csrftoken'] = Cookies.get('csrftoken')
}).catch(error => {
return Promise.reject(error.response.data)
})
}
}
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.
Here's the view that returns the token incase youre curios:
class CSRFTokenView(APIView):
permission_classes = (permissions.AllowAny,)
@method_decorator(ensure_csrf_cookie)
def get(self, request):
return HttpResponse()
I realize I might be mixing problems here, but any suggestions that could help me trouble shoot this are welcome.