Last active
December 26, 2017 23:56
-
-
Save takeshy/4509095 to your computer and use it in GitHub Desktop.
Node.js with Backbone.js for CSRF Protection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
app.use(express.session()); | |
app.use(express.csrf()); | |
app.get('/', index); | |
index = function(req,res,next){ | |
res.render('index',{token: req.session._csrf}); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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