Csrf verification failed - Django Rest and Backbone.js [duplicate] - javascript

This question already has answers here:
Got CSRF verification failure when while requesting POST through API
(2 answers)
Closed 5 years ago.
I have started going through "Lightweight Django" https://github.com/lightweightdjango to learn more about Django and Client-Side JavaScript. During testing out the LoginView created using Backbone.js I get the Forbidden(403) CSRF verification failed.Request aborted. message, as pointed out in this post: CSRF verification failing in django/backbone.js .
First of all I thought of inserting {% csrf_token %} template tag in the form but when I do this the server is giving me a POST / HTTP/1.1" 405 0 - Method Not Allowed (POST) : / message.
Since the AJAX X-CSRFToken request header is being set using $.ajaxPrefilter(), I can't figure out what the problem is.
When I am using httpie to perform POST requests using the superuser details, everything works just fine as in the following example:
HTTP/1.0 200 OK
Allow: POST, OPTIONS
Content-Type: application/json
Date: Mon, 11 Sep 2017 13:49:49 GMT
Server: WSGIServer/0.2 CPython/3.6.2
Vary: Cookie
X-Frame-Options: SAMEORIGIN
{
"token" : some_value
}
Making use of the console from the "Inspect Element" feature I get the following messages:
Response headers:
Allow: GET, HEAD, OPTIONS
Content-Length: 0
Content-Type: text/html; charset=utf-8
Date: Mon, 11 Sep 2017 14:03:06 GMT
Server: WSGIServer/0.2 CPython/3.6.2
X-Frame-Options: SAMEORIGIN
Request headers:
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.5
Connection: keep-alive
Content-Length: 116
Content-Type: application/x-www-form-urlencoded
Cookie: csrftoken=some_value
Host: 127.0.0.1:8000
Referer: http://127.0.0.1:8000/
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:55.0) Gecko/20100101 Firefox/55.0
I don't know if the TemplateView is to blame or I am missing something:
urls.py:
from django.conf.urls import url,include
from django.views.generic import TemplateView
#from django.views.decorators.csrf import ensure_csrf_cookie
from rest_framework.authtoken.views import obtain_auth_token
from board.urls import router
urlpatterns = [
url(r'^api-auth/', obtain_auth_token, name='api-login'),
url(r'^api-root/', include(router.urls)),
url(r'^$', TemplateView.as_view(template_name='board/index.html')),
]
Can someone explain what is actually going on?
Thanks!

Fore every POST request you need to send CSRF token to your django backend in Django weebasite u can fined ajaxSetup for your frontend (backbone.js). Just create new file ajaxSetup.js and past this code.
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
function sameOrigin(url) {
// test that a given url is a same-origin URL
// url could be relative or scheme relative or absolute
var host = document.location.host; // host + port
var protocol = document.location.protocol;
var sr_origin = '//' + host;
var origin = protocol + sr_origin;
// Allow absolute or scheme relative URLs to same origin
return (url == origin || url.slice(0, origin.length + 1) == origin +
'/') ||
(url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin +
'/') ||
// or any other URL that isn't scheme relative or absolute i.e relative.
!(/^(\/\/|http:|https:).*/.test(url));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) {
// Send the token to same-origin, relative URLs only.
// Send the token only if the method warrants CSRF protection
// Using the CSRFToken value acquired earlier
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
You can read about this in django official website CSRF TOKEN

Related

get method working, but not post - ZapWorks Studio

I'm using zapworks studio to develop an AR experience. It uses Z.ajax to make the ajax calls. I make a GET request and a POST request. I'm also using smileupps to host couchdb(they have free hosting). Here's the CORS configuration:
credentials: false; headers:Accept, Authorization, Content-Type, Origin;
methods: GET,POST,PUT,DELETE,OPTIONS,HEAD; origins: *
Everything works fine when launching ZapWorks Studio on windows. When scanning the zapcode with an android device, however, the post ajax call fails. Only the post. I am using basic authentication. I enforce that only the admin can manage the database on couchdb. I can access the host from both the desktop and the phone from a web browser to do everything manually.
I tried everything I could of to solve the problem: remove authentication, change the CORS configuration...nothing works. I thought it was an issue with CORS but everything works fine on windows and on the mobile just the POST fails...I keep getting a status code of 0.
EDIT - New info, testing on apitester also works on the desktop and mobile.
EDIT - Here's the zpp to show the logic
EDIT - Tried with REST Api Client on my phone and it worked as well. This can only be a CORS issue or something with zapworks. Weird that it works on windows but not on the phone.
EDIT - I found out what the problem is, but not how to fix it. So I set a proxy to debug the requests made from zapworks studio following this tutorial. It seems that it does a preflight request but gets the response
"HTTP/1.1 405 Method Not Allowed"
even though the payload is
{"error":"method_not_allowed","reason":"Only DELETE,GET,HEAD,POST
allowed"}.
Here's the request:
OPTIONS /ranking HTTP/1.1
Host: somehost.com
Connection: keep-alive
Access-Control-Request-Method: POST
Origin: null
User-Agent: Mozilla/5.0 (Linux; Android 8.0.0; SM-G950U1 Build/R16NW; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/67.0.3396.87 Mobile Safari/537.36
Access-Control-Request-Headers: authorization,content-type,x-requested-with
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: en-US
X-Requested-With: com.zappar.Zappar
and the response:
HTTP/1.1 405 Method Not Allowed
Server: CouchDB/1.6.0 (Erlang OTP/R15B01)
Date: Mon, 18 Jun 2018 21:22:12 GMT
Content-Type: text/plain; charset=utf-8
Content-Length: 76
Cache-Control: must-revalidate
Allow: DELETE,GET,HEAD,POST
Access-Control-Expose-Headers: Cache-Control, Content-Type, Server
Access-Control-Allow-Origin: null
Connection: keep-alive
{"error":"method_not_allowed","reason":"Only DELETE,GET,HEAD,POST allowed"}
which clearly shows that POST is allowed...
On the windows side, there doesn't seem to be a preflight request for some reason and my guess is that's why it works. Now the question is how do I configure CORS on couchdb to work on android. These are the configurations available:
enable_cors: true
credentials: false
headers:Accept, Authorization, Content-Type, Origin
methods:GET,POST,PUT,DELETE,OPTIONS,HEAD
origins:*
This is the code:
const Open_SansRegular_ttf0 = symbol.nodes.Open_SansRegular_ttf0;
parent.on("ready", () => {
const Plane0 = symbol.nodes.Plane0;
let ajaxParameters : Z.Ajax.Parameters = {
url: "https://something.smileupps.com/test/_all_docs?include_docs=true",
headers: {"Authorization": "Basic my64encoding"},
method: "GET",
timeout: 3000
};
// Perform the AJAX request
Z.ajax(ajaxParameters, (statusCode, data, request) => {checkRequest(statusCode, data);});
ajaxParameters = {
url: "https://something.smileupps.com/test",
headers: {"Content-Type":"application/json", "Authorization": "Basic my64encoding"},
method: "POST",
body: '{"name" : "asdasd", "something": 234}',
timeout: 3000
};
Z.ajax(ajaxParameters, (statusCode, data, request) => {checkRequest(statusCode, data);});
});
function checkRequest(statusCode, data) {
if (statusCode === 0) {
Open_SansRegular_ttf0.text("Unable to connect - check network connection.");
console.log("Unable to connect - check network connection.");
return;
}
if (statusCode < 200 || statusCode >= 300) {
Open_SansRegular_ttf0.text("HTTP request failed: " + statusCode);
console.log("HTTP request failed: " + statusCode);
return;
}
// Attempt to parse the data returned from the AJAX request as JSON
let parsedData;
try {
// https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
parsedData = JSON.parse(data);
} catch (e) {
Open_SansRegular_ttf0.text("Unable to parse JSON: " + e);
console.log("Unable to parse JSON: " + e);
return;
}
return parsedData;
}
EDIT
Here's the request on windows
Accept:*/*
Accept-Encoding:gzip, deflate
Accept-Language:en-US
Authorization:Basic mybase64encoding
Connection:keep-alive
Content-Length:37
Content-Type:application/json
Host:http://something.smileupps.com/test
Origin:file://
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) ZapWorksStudio/4.0.4-stable Chrome/58.0.3029.110 Electron/1.7.9 Safari/537.36
X-DevTools-Request-Id:3680.9
X-Requested-With:XMLHttpRequest
and the response:
Access-Control-Allow-Origin:file://
Access-Control-Expose-Headers:Cache-Control, Content-Type, ETag, Server
Cache-Control:must-revalidate
Content-Length:95
Content-Type:text/plain; charset=utf-8
Date:Mon, 18 Jun 2018 21:36:22 GMT
ETag:"1-512f89feb3d0a88781119e772ec6fd7b"
Location:http://something.smileupps.com/test
Server:CouchDB/1.6.0 (Erlang OTP/R15B01)
No preflight.
Your problem is in the request: Origin: null is usually what you get when the Web page containing the xhr request is opened with the file: rather than the http or https protocol. You won't get any successful CORS request with such an origin.

Firefox is parsing empty response payload

We're making an XHR request with the following headers (I've simplified a bit):
POST http://localhost:9001/login
Host: localhost:9001
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:51.0) Gecko/20100101 Firefox/51.0
Accept: application/json, text/plain, */*
Content-Type: application/json;charset=utf-8
Content-Length: 67
Then our server responds like this (again simplified):
Status code: 200 OK
Cache-Control: no-cache, no-store
Connection: close
Content-Length: 0
Date: Mon, 27 Feb 2017 17:19:53 GMT
Server: WildFly/9
Set-Cookie: JSESSIONID=123; path=/
There's no payload in the response. Note the Content-Length: 0. But Firefox still tries to parse it as XML. And outputs the following error to the console:
XML Parsing Error: no root element found
Location: http://localhost:9001/login
Line Number 1, Column 1
Note, the server doesn't send a content-type header. And according to RFC 7231 it only has to send a content-type header when there is actual content.
So is this a bug in Firefox or is my research faulty?
Reproducing it yourself
I've written a small server and client to reproduce the problem.
server.js (start with node ./server.js):
const fs = require('fs'), http = require('http');
const server = http.createServer(function (request, response) {
if (request.method === 'POST') {
// send empty response
response.end();
return;
}
// send file content
fs.readFile('.' + request.url, function (error, content) {
response.writeHead(200, { 'Content-Type': request.url === '/index.html' ? 'text/html' : 'text/javascript' });
response.end(content);
});
}).listen(8080);
index.html
<script src="client.js"></script>
client.js
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost:8080/login');
xhr.send();
When opening the URL http://localhost:8080/index.html in Firefox, there will be an error in the JavaScript console.
Firefox Version 51.0.1
There's no payload in the response. Note the Content-Length: 0
That means there is a payload, and that payload is 0 bytes in size. Consider the difference between null and "" as strings. What you have here is the equivalent of "" when you want the equivalent of null.
Set the status code to 204 rather than 200 to indicate you aren't sending an entity (and remove the content-type, since there's no content-type with no entity).
(For a long time Firefox would still log an error for this case, but thankfully this is finally fixed. Even when it did log the error it would still continue to run any scripts correctly).
Judging from the POST request it seems that you are using XHR/JS to send the request.
So the problem is likely in the code that is processing the result.
(Also, the Content-Type in the request is incorrect, there's no charset parameter on application/json)

CSRF Mismatch When POSTing from Ember to Sails Backend

First off, I just wanted to say that I have read through all of the other threads relating to this topic, but haven't had any luck. Here's a breakdown of the issue:
Goals
Retrieve a CSRF token from Sails when the Ember Application starts
Inject that CSRF token into every AJAX request that is initiated from the Ember Application
To satisfy goal 1, I created an Ember Initializer that runs when the application first boots up (if there is a better place for this, I'm totally open to suggestions). To satisfy goal 2, I retrieve the CSRF token from Sails and then attempt to use Ember.$.ajaxSetup() to ensure the CSRF token is passed either as a header (X-CSRF-Token) or parameter (_csrf). I also ensure that I'm using the withCredentials option to ensure the cookie is set. Here's the code:
// initializers/csrf.js
import Ember from 'ember';
import config from '../config/environment';
export function initialize() {
Ember.$.get(config.APP.API_URL + '/csrfToken').then(function(result) {
Ember.$.ajaxSetup({
data: {
'_csrf': result._csrf
},
xhrFields: { withCredentials: true }
});
}, function(error) {
console.log(error);
});
}
export default {
name: 'csrf',
initialize: initialize
};
All of this appears to work as I can see in Chrome dev tools that the CSRF token is being retrieved and when I make an AJAX request, I see the data appended to the POST data or added as a header (tried both options). Here's the code I'm running and all of the associated headers:
Ember.$.post(config.APP.API_URL + '/auth/register', {
'email': _this.get('email'),
'password': _this.get('password')
}).then(function(response) {
console.log('It worked!');
});
Request Headers
POST /auth/register HTTP/1.1
Host: localhost:1337
Connection: keep-alive
Content-Length: 82
Accept: */*
Origin: http://localhost:4200
CSP: active
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.130 Safari/537.36
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
DNT: 1
Referer: http://localhost:4200/signup
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8
Cookie: sails.sid=s%3AbrABhErTY3-ytTWOKFJ2KBj7DCAzaLDc.apD60Sd%2BW85GSbTfJ7E3B2PrUwnhOsW6GlNpZTu9jFg
Form Data
_csrf:yP7GDiU2-YGmLBfBvQtMPT3-hRpnfK0x-AfA
email:test#test.com
password:q1w2e3r4
Response Headers
HTTP/1.1 403 Forbidden
Vary: X-HTTP-Method-Override
Access-Control-Allow-Origin: http://localhost:4200
Access-Control-Allow-Credentials: true
Content-Type: text/html; charset=utf-8
Content-Length: 13
Date: Thu, 09 Jul 2015 08:11:34 GMT
Connection: keep-alive
As you can see from the Response headers, I end up receiving a 403 Forbidden - CSRF Mismatch from Sails. Now, here's where it gets a little weird: first, I'm able to run this just fine with Postman. I retrieve a token and then post that token along with the data to the /auth/register url and it works as expected.
I'm also tried removing the initializer and running the following code:
Ember.$.ajaxSetup({
xhrFields: { withCredentials: true }
});
Ember.$.get(config.APP.API_URL + '/csrfToken').then(function(result) {
Ember.$.post(config.APP.API_URL + '/auth/register', {
'email': _this.get('email'),
'password': _this.get('password'),
'_csrf': result._csrf
}).then(function(response) {
console.log('It worked!');
});
});
This works. However, at this point, I'm at somewhat of a loss as to what the issue actually is. Appreciate any help I can get.
Thanks in advance!
James
#jdixon04, Can you try URL-encoding the CSRF token before sending it through POST? The token mismatch will occur if the token is getting altered from the original.
I found this issue in Github: https://github.com/balderdashy/sails/issues/2266.
I hope this will solve your issue. Do try it and let me know if it works. Thanks.
#jdixon04, got here from your post on my github issue. Actually, isn't the CSRF token going to change at each request made to the server? Then you approach to fix the token when the frontend load cannot cope with this, you may have to fetch the token before each request and use ajaxPrefilter to pass it to the request.
Is that actually related to ember-data-sails? It seems to me you're doing pure ajax here! If you look in my config, you'll realise that pure ajax calls (for authentication as well) are exempted from csrf as I could not make it work as I wished :\ .
Add the x-csrf-token header like this:
Ember.$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': result._csrf
},
xhrFields: { withCredentials: true }
});

AJAX function w/ Mailgun, getting "ERROR Request header field Authorization is not allowed by Access-Control-Allow-Headers"

I'm working on making an AJAX call that hit the Mailgun API to send email. Documentation on Mailgun says that post requests should be made to "https://api.mailgun.net/v3/domain.com/messages". I've included my api key as specified by mailgun (they instruct to use a username of 'api'). Since this involves CORS, I can't get past the error: Request header field Authorization is not allowed by Access-Control-Allow-Headers.
However, I've inspected the requests/responses in the Network tab and "Access-Control-Allow-Origin" in the response from Mailgun is set to "*"...which should indicate that it should allow it? (See request/response below): I've edited the actual domain and my API key.
Remote Address:104.130.177.23:443
Request URL:https://api.mailgun.net/v3/domain.com/messages
Request Method:OPTIONS
Status Code:200 OK
Request Headersview source
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:accept, authorization
Access-Control-Request-Method:POST
Connection:keep-alive
Host:api.mailgun.net
Origin:null
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36
Response Headersview source
Access-Control-Allow-Headers:Content-Type, x-requested-with
Access-Control-Allow-Methods:GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Origin:*
Access-Control-Max-Age:600
Allow:POST, OPTIONS
Connection:keep-alive
Content-Length:0
Content-Type:text/html; charset=utf-8
Date:Fri, 20 Mar 2015 19:47:29 GMT
Server:nginx/1.7.9
My code for the ajax call is below, in which I include my credentials in the headers and the domain to where the post is supposed to go. Not sure what's causing this not to work. Is it because I'm testing on local host? I didn't think that would make a difference since the "Access Control Allow Origin:*" in the response header. Any help would be greatly appreciated! Thank you.
function initiateConfirmationEmail(formObj){
var mailgunURL;
mailgunURL = "https://api.mailgun.net/v3/domain.com/messages"
var auth = btoa('api:MYAPIKEYHERE');
$.ajax({
type : 'POST',
cache : false,
headers: {"Authorization": "Basic " + auth},
url : mailgunURL,
data : {"from": "emailhere", "to": "recipient", etc},
success : function(data) {
somefunctionhere();
},
error : function(data) {
console.log('Silent failure.');
}
});
return false;
}
Drazisil is correct above. The response needs to include Access-Control-Allow-Headers: Authorization as you are including that header in your request and Authorization is not a simple header.

Only GET working in cross domain API request with django-piston

I'm not able to do POST/PUT/DELETE cross-domain request on my API using django-piston, I've CORS enabled using this script (based on this):
class CORSResource(Resource):
"""
Piston Resource to enable CORS.
"""
# headers sent in all responses
cors_headers = [
('Access-Control-Allow-Origin', '*'),
('Access-Control-Allow-Headers', 'AUTHORIZATION'),
]
# headers sent in pre-flight responses
preflight_headers = cors_headers + [
('Access-Control-Allow-Methods', '*'),
('Access-Control-Allow-Credentials','true')
]
def __init__(self, handler, authentication=None):
super(CORSResource, self).__init__(handler, authentication)
self.csrf_exempt = getattr(self.handler, 'csrf_exempt', True)
def __call__(self, request, *args, **kwargs):
request_method = request.method.upper()
# intercept OPTIONS method requests
if request_method == "OPTIONS":
# preflight requests don't need a body, just headers
resp = HttpResponse()
# add headers to the empty response
for hk, hv in self.preflight_headers:
resp[hk] = hv
else:
# otherwise, behave as if we called the base Resource
resp = super(CORSResource, self).__call__(request, *args, **kwargs)
# slip in the headers after we get the response
# from the handler
for hk, hv in self.cors_headers:
resp[hk] = hv
return resp
#property
def __name__(self):
return self.__class__.__name__
In the frontend I'm using Backbone with JSONP activated. I don't have any errors, the OPTIONS request works fine then nothing happens. I tried to change the « Access-Control-Allow-Methods » but it doesn't change anything. Any idea ?
Edit:
Here is the request headers of an OPTIONS request:
OPTIONS /api/comments/ HTTP/1.1
Host: apitest.dev:8000
User-Agent: Mozilla/5.0 (X11; Linux i686; rv:12.0) Gecko/20100101 Firefox/12.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
DNT: 1
Connection: keep-alive
Origin: http://3l-oauth.dev:1338
Access-Control-Request-Method: POST
Access-Control-Request-Headers: authorization,content-type
Pragma: no-cache
Cache-Control: no-cache
and the response headers:
HTTP/1.0 200 OK
Date: Sat, 12 May 2012 09:22:56 GMT
Server: WSGIServer/0.1 Python/2.7.3
Access-Control-Allow-Methods: *
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: AUTHORIZATION
Content-Type: text/html; charset=utf-8
X-Frame-Options: SAMEORIGIN
JSONP is GET only:
You cannot make POST, PUT, or DELETE requests cross-domain. Cross domain JavaScript is facilitated through the use of <script> tags that send requests to your server for dynamic JavaScript. script tags are GET requests only.
However, one of the recommended methods for adjusting to this limitation when dealing with cross-domain JavaScript is to use a method query parameter that you would use in your server-side code to determine how you should handle a specific request.
For instance, if the request was
POST /api/comments/
then you could do this:
/api/comments?method=POST
Under the hood, it's still a GET request, but you can achieve your goal with slight modifications to your API.
When determining the type of request, instead of checking the HTTP Method:
if request_method == "OPTIONS":
Check the request parameter "method" instead:
if request.GET["method"] == "OPTIONS":
JSONP Requests Must return JavaScript:
The other really important point to take note of is that your JSONP requests must all return JavaScript wrapped (or padded) in a function call. Since the requests are made under the hood by script tags that expect JavaScript, your server must return content that the browser understands.
If this doesn't make sense to you or you need more information, there is a great explanation here on how JSONP and script tag remoting works under the hood.

Categories

Resources