我一直在努力实施CSRF令牌,我不知道我做错了什么。
server.js:
// set up ======================================================================
var express = require('express');
var port = process.env.PORT || 8080;
var mongoose = require('mongoose');
var fs = require('fs');
var csrf = require('csurf');
.
.
.
var app = express();
app.use(csrf());
app.use(function(req, res, next) {
res.locals.token = req.csrfToken();
next();
});
.
.
.
login.ejs:
<form action="/login" method="post">
<!--form fields-->
</form>
.
.
.
<input type="hidden" name="_csrf" value="<%= token %>">
当我尝试打开登录页面时,我在node.js控制台中获得以下内容:
token is not defined
.
.
.
GET /login 500 93ms - 1.64kb
\
编辑:server.js现在看起来像这样:
var express = require('express');
var port = process.env.PORT || 8080;
var mongoose = require('mongoose');
var fs = require('fs');
var csrf = require('csurf');
.
.
.
var app = express();
require('./config/express')(app, __dirname);
require('./config/routes')(app);
app.use(csrf());
app.use(function(req, res, next) {
res.locals.token = req.csrfToken();
next();
});
现在加载登录页面,但未定义CSRF令牌。
答案 0 :(得分:1)
您在表单中的价值是错误的。
它不应该只是
value =“&lt;%= token%&gt;”
但是
value =“&lt;%= csrfToken%&gt;”
答案 1 :(得分:0)
尝试:
首先安装csurf模块(https://github.com/expressjs/csurf):
$ npm install csurf
server.js中的
var router = express.Router();
var csrf = require('csurf');
var csrfProtection = csrf();
router.use(csrfProtection);
router.get('/user/login/', function(req, res, next){
res.render('user/login', {csrfToken: req.csrfToken()});
});
在login.ejs中:
<input type="hidden" name="_csrf" value="<% csrfToken >">