Django rest framework + axios: Invalid preflight http method on first request - django

We have a rather strange situation with a react based frontend using axios to talk to our Django rest framework based backend.
When logging in a preflight OPTIONS request is sent by axios (as expected) but the first time the backend receives it, it seems to be malformed and thus results in a 401.
However if I the retry, or even replay the exact same request using the browsers dev tool, the backend accepts the OPTIONS request and everything works as expected. We can consistently reproduce this.
The Django development server log looks like this:
First request
[23/Jan/2019 15:43:42] "{}OPTIONS /backend/api/auth/login/ HTTP/1.1" 401
Subsequent Retry
[23/Jan/2019 15:43:52] "OPTIONS /backend/api/auth/login/ HTTP/1.1" 200 0
[23/Jan/2019 15:43:52] "POST /backend/api/auth/login/ HTTP/1.1" 200 76
So as you can see, curly braces are added in the request method, which means that the request is not considered to be an OPTIONS request, and therefore a 401 is returned.
The django view
class LoginView(KnoxLoginView):
authentication_classes = [BasicAuthentication]
# urls.py (extract)
path('auth/login/', LoginView.as_view(), name='knox_login'),
The Axios request
axios.post('/backend/api/auth/login/', {}, {
headers: {
'Authorization': 'Basic ' + window.btoa(creds.username + ":" + creds.password)
}
}).then((response) => {
dispatch({type: 'SIGNIN_SUCCESS', response})
}).catch((err) => {
dispatch({type: 'SIGNIN_ERROR', err})
})
Some package version info
Django==2.1.4
django-cors-headers==2.4.0
django-debug-toolbar==1.11
django-extensions==2.1.4
django-rest-knox==3.6.0
django-rest-passwordreset==0.9.7
djangorestframework==3.9.0
axios#0.18.0

Related

CSRF Verification fails in production for Cross Domain POST request

The HTTP_X_CSRFTOKEN header does not match what is inside the csrftoken cookie.
How can I examine the cookie? Set-Cookie is not displayed in the Response header for Cross Domain requests.
I have already followed instructions found in:
CSRF with Django, React+Redux using Axios
Interestingly I found "X-CSRFTOKEN" translates to "HTTP_X_CSRFTOKEN" on the server request header.
Works fine in the development env under localhost (although I am using 2 different ports - one for django and the other my frontend).
UPDATE:
It seems the csrktoken cookie is not correctly set for cross domain rquests (although the browser displays it in the Request Header) so the X-CSRFTOKEN does not get sent.
I ended up adding an API call to return the current csrftoken using a GET request and then sending it back using the X-CSRFTOKEN header.
You haven't mentioned how you're getting the csrftoken from the server in the first place, so I'm assuming it's already present in your browser.
Along with the X-CSRFToken header, also include the cookies in the request using withCredentials: true.
I'm using the js-cookie library to get the csrftoken from the cookies.
import Cookies from 'js-cookie';
axios({
url: 'http://localhost:8000/graphql',
method: 'post',
withCredentials: true,
data: {
query: `
{
// Your query here
}
`
},
headers: {
"X-CSRFToken": Cookies.get('csrftoken')
}
})
Also add CORS_ALLOW_CREDENTIALS = True to your settings.py, assuming you are using django-cors-headers. Otherwise, the cookies won't be accepted.
You will have to make the X-CSRFTOKEN header accessible via the CORS Access-Control-Expose-Headers directive. Example:
Access-Control-Expose-Headers: X-CSRFTOKEN
This header has to be set by your API or web server, so that the browser will see it during the CORS preflight request.

Axios is adding a prefix to the api target url

I know this may be the dumpest question ever asked, however it really got me this hopeless :(
I have the React front End with a simple property in package.json
"proxy": "http://localhost:5000/"
which I believe is redirecting all api sent through axios to that servr address.
My axios request is
const canvas_type="standard"
axios.post('api/v1/new_canvas',{
canvas_type
})
}
The backend flask api is:
#api_bp.route("/new_canvas", methods=["POST"])
#requires_auth
def get_new_cavas():
"""working code"""
The code works perfectly when tested with Postman,
but when I call the axios, I get this line in the server output
127.0.0.1 - - [01/Sep/2018 23:51:12] "POST /designer/api/v1/new_canvas HTTP/1.1" 405 -

Vue.js frontend interacting with Flask backend CORS issues due to not allowed preflight headers

I am stuck with the following error message in the Chrome browser:
Failed to load http://localhost:5000/my_endpoint: Request header field
Access-Control-Allow-Origin is not allowed by
Access-Control-Allow-Headers in preflight response.
The browser is loading a webpage from a Vue.js frontend app with webpack etc. and vue-resource to perform HTTP requests to the REST backend.
The URL http://localhost:5000/my_endpoint is a HTTP GET/POST endpoint served by a python Flask application.
On the frontend Javascript I have these CORS settings:
import VueResource from 'vue-resource'
Vue.use(VueResource)
Vue.http.options.crossOrigin = true
Vue.http.headers.common['Access-Control-Allow-Origin'] = '*'
On the backend python code in the Flask app I have the following CORS configuration details:
#app.after_request
def add_header(response):
response.headers['Access-Control-Allow-Origin'] = '*'
response.headers['Access-Control-Allow-Headers'] = 'Access-Control-Allow-Headers, Origin, X-Requested-With, Content-Type, Accept, Authorization'
response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS, HEAD'
response.headers['Access-Control-Expose-Headers'] = '*'
return response
When performing this HTTP POST request in the Javascript frontend:
this.$http.post("http://localhost:5000/my_endpoint", { my_custom_key: "my custom value"})//, {emulateJSON: true})
.then((response) => {
// do stuff
})
where { my_custom_key: "my custom value"} is the JSON body of the HTTP POST request, then in the Flask backend for some reason I see an HTTP OPTIONS request coming, cf. the Flask log:
127.0.0.1 - - [26/Jun/2018 21:45:53] "OPTIONS /ad HTTP/1.1" 200 -
There must be some sort of back/forth ceremony to honor before being able to retrieve the JSON data from the backend, but I am lost in these details.
On the internet I've seen all sorts of explanations, and I've been playing a bit with the vue-resource configuration details like:
adding/removing {emulateJSON: true} to the HTTP POST request
adding/removing Vue.http.options.xhr = { withCredentials : true }; to the configuration of Vue.js
but I am not able retrieve the JSON data coming from the backend.
Searching for "CORS" on the Vue.js documentation or on https://github.com/pagekit/vue-resource does not give any information on how to fix these issues with Cross-origin resource sharing (CORS).
How do I get a Vue.js frontend working with a Flask backend on these CORS issues?
The solution was to remove from the frontend: Vue.http.headers.common['Access-Control-Allow-Origin'] = '*' (which actually does not make sense as it's an HTTP header that usually goes into the response from the backend).
Also to clean up a bit more the backend I found out that response.headers['Access-Control-Expose-Headers'] = '*' was not needed. Probably the other HTTP headers could be more slim, but for now I keep them as they are.

CSRF exempt on REST View

I am serving an API which will be accessible with a small sensor sending a POST request with data. This sensor has a limited software, and I want to disable the CSRF protection on my API view.
So I've added the decorator:
url(
regex=r'^beacons/$',
view=csrf_exempt(ScanListCreateAPIView.as_view()),
name='beacons'
),
Unfortunately, when I perform a POST with my sensor, I still get a 403 error:
<h1>Forbidden <span>(403)</span></h1>
<p>CSRF verification failed. Request aborted.</p>
<p>You are seeing this message because this HTTPS site requires a 'Referer
header' to be sent by your Web browser, but none was sent
. This header is
required for security reasons, to ensure that your browser is not being
hijacked by third parties.</p>
<p>If you have configured your browser to disable 'Referer' headers, please
re-enable them, at least for this site, or for HTTPS connections, or for
'same-origin' requests.</p>
I've try to add a "Referer: " null header in my POST request, but I still have a 403 response, mentionning that CSRF failed.
My request is:
POST /api/beacons HTTP/1.1
Host: vincent.pythonanywhere.com
Content-Type: application/json
Accept: */*
User-Agent: Mozilla/4.0 (compatible; esp8266 Lua; Windows NT 5.1)
Content-Length: 597
{"beacon":"aaa"," ...
The same request passed throught curl is working ok, with a 201 response.
Here is the solution to diable CSRF:
1- As DRF does its own csrf with SessionAuth, you have to specify in the view:
authentication_classes = (BasicAuthentication,)
2- Then I don't know exacly why, but view=csrf_exempt(ScanListCreateAPIView.as_view()), in urls doesn't work. Instead, use the braces mixin:
from braces.views import LoginRequiredMixin, CsrfExemptMixin
class ScanListCreateAPIView(ListCreateAPIView, CsrfExemptMixin):
authentication_classes = (BasicAuthentication,)

Ajax, CSRF and DELETE

I use the getCookie function from the django documentation to get the csrfmiddlewaretoken value.
I have the following ajax call:
var url = reverse_removeprofile.replace(/deadbeef/, key);
$.ajax({
type: "DELETE",
url: url,
data: "csrfmiddlewaretoken=" + getCookie("csrftoken"),
success: function() { ... },
});
When this code gets executed then django raises a 403 exception telling me that the CSRF verification failed. However, if I change the type from DELETE to POST then django is happy about it and doesn't complain at all.
I was not really able to find something useful in Google about this, but I've found this (now closed and fixed) ticket: https://code.djangoproject.com/ticket/15258
If I understand it correctly then this issue has been fixed in the 1.4 milestone. I use django 1.4 but still I cannot verify the CSRF token with a DELETE request.
Am I missing something here?
This appears to be a jQuery bug, caused by some confusion as to whether DELETE data should be attached to the URL (like a GET request) or the request body (like a POST)
See this bug report.
You can probably get around this by using the alternative CSRF method for AJAX calls, setting an X-CSRFToken header on the request. Try changing your AJAX call to look like this:
$.ajax({
type: "DELETE",
url: url,
beforeSend: function(xhr) {
xhr.setRequestHeader("X-CSRFToken", getCookie("csrftoken"));
},
success: function() { ... },
});
Please note, when it comes to DELETE requests DJango does not check for csrfmiddlewaretoken in the request body. Rather it looks for X-CSRFToken header
Coming to working of DJango CSRFMiddleware you can see the source code of django > middleware > csrf.py > CsrfViewMiddleware in which it is very clear that DJango does not scan for csrfmiddlewaretoken in request body if the request is of DELETE type:
# Check non-cookie token for match.
request_csrf_token = ""
if request.method == "POST":
try:
request_csrf_token = request.POST.get('csrfmiddlewaretoken', '')
except OSError:
# Handle a broken connection before we've completed reading
# the POST data. process_view shouldn't raise any
# exceptions, so we'll ignore and serve the user a 403
# (assuming they're still listening, which they probably
# aren't because of the error).
pass
if request_csrf_token == "":
# Fall back to X-CSRFToken, to make things easier for AJAX,
# and possible for PUT/DELETE.
request_csrf_token = request.META.get(settings.CSRF_HEADER_NAME, '')