Created
August 28, 2014 15:38
-
-
Save fwon/e069f6ded68b4390470a to your computer and use it in GitHub Desktop.
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
// 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