Create a gist now

Instantly share code, notes, and snippets.

@takeshy /app.js
Last active Dec 16, 2015

Node.js with Backbone.js for CSRF Protection
app.use(express.session());
app.use(express.csrf());
app.get('/', index);
index = function(req,res,next){
res.render('index',{token: req.session._csrf});
}
Backbone.ajax = function() {
var data = {};
if (arguments[0].type && arguments[0].type !== "GET") {
arguments[0].contentType = "application/json";
if (arguments[0].data) {
if (typeof arguments[0].data === "string") {
data = JSON.parse(arguments[0].data);
} else {
data = arguments[0].data;
}
}
data["_csrf"] = Backbone.CSRFToken;
arguments[0].data = JSON.stringify(data);
}
return Backbone.$.ajax.apply(Backbone.$, arguments);
}
<!DOCTYPE html>
<html>
<head>
<link rel='stylesheet' href='/stylesheets/style.css' />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://underscorejs.org/underscore-min.js"></script>
<script type="text/javascript" src="http://backbonejs.org/backbone-min.js"></script>
<script type="text/javascript" src="/javascript/backbone-csrf.js"></script>
<script type="text/javascript">
jQuery(function() {
window.Backbone.CSRFToken = "<%- token %>";
window.router = new MyRouter();
Backbone.history.start();
});
</script>
</head>
<body>
<div id="main">
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment