Skip to content

Instantly share code, notes, and snippets.

@fwon
Created August 28, 2014 15:38
Show Gist options
  • Save fwon/e069f6ded68b4390470a to your computer and use it in GitHub Desktop.
Save fwon/e069f6ded68b4390470a to your computer and use it in GitHub Desktop.
// Node.js请求 CSRF防范
var generateRandom = function(len) {
return crypto.randomBytes(Math.ceil(len * 3 / 4))
.toString('base64')
.slice(0, len);
};
// 为每个请求的用户,在Session中赋予一个随即值
<form id="test" method="POST" action="http://domain_a.com/guestbook">
<input type="hidden" name="content" value="xxx"/>
<input type="hidden" name="_csrf" value="<%=_csrf%>"/>
</form>
// 后端做校验
function(req, res) {
var token = req.session._csrf || (req.session._csrf = generateRandom(24));
var _csrf = req.body._csrf;
if(token !== _csrf) {
res.writeHead(403);
res.end("禁止访问");
} else {
handle(req, res);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment