[开发环境] nodejs v4.2.4 + expressjs v4.13.1 + csurf v1.8.3
我成功安装了csurf中间件,但似乎无法正常工作。 我尝试提交没有csrf输入字段的表单来测试它的工作原理并没有错误。所以我将console.log代码插入路由器js文件
的console.log(res.locals._csrf);
我收到了#undefined'。
我插入输入字段以验证值是否存在,html结果也没有csrfToken
<input name="_csrf" value="" type="hidden">
我该怎么办?这是html源
<form class="form" method="post" action="/login" role="form">
<input type="hidden" name="_csrf" value="{{_csrf}}">
<div class="form-group label-floating">
<label class="control-label" for="focusedInput1">User Name</label>
<input class="form-control" name="userName" id="focusedInput1" type="text">
</div>
<div class="form-group">
<div class="form-group label-floating">
<label class="control-label" for="focusedInput2">password</label>
<input class="form-control" name="user_pw" id="focusedInput2" type="password">
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary" style="float:left">Login</button>
<button type="button" class="btn btn-default" style="float:right" data-dismiss="modal">Cancel</button>
</div>
</form>
,这是app.js
// module importing
var express = require('express'),
path = require('path'),
favicon = require('serve-favicon'),
logger = require('morgan'),
cookieParser = require('cookie-parser'),
bodyParser = require('body-parser'),
exphbs = require('express-handlebars'),
mongoose = require('mongoose'),
csrf = require('csurf');
const session = require('express-session');
const MongoStore = require('connect-mongo')(session);
var routes = require('./routes/index');
var users = require('./routes/users');
var credentials = require('./credentials.js');
var app = express();
// mongoose Setup
mongoose.connect(credentials.mongooseRsrc.collUrl);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('.hbs', exphbs({defaultLayout: 'single', extname: '.hbs'}));
app.set('view engine', '.hbs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser(credentials.cookieSecret));
app.use(session({
resave: false,
saveUninitialized: false,
secret: 'sfbsesc',
store: new MongoStore({
mongooseConnection: mongoose.connection
})
}));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
app.use(csrf());
app.use(function(req, res, next){
res.locals._csrf = req.csrfToken();
});
//skip
答案 0 :(得分:0)
我遇到了同样的问题,并通过控制器传递令牌来解决这个问题。
在路径控制器中,对于POST / login,将响应中的标记作为对象传递。
router.post('/login', (req, res) => {
res.render('login', {
_csrfToken: req.csrfToken(),
});
});
这可能会导致其他路线出现问题,具体取决于他们的设置方式,但如果您遇到错误,说明令牌无效,您可能只需要将其传递到该路线