ForbiddenError:无效的csrf令牌,表达js

时间:2015-08-08 13:51:16

标签: javascript node.js express csrf csrf-protection

我试图让csurf工作,但似乎偶然发现了什么。到目前为止,代码如下所示:

index.ejs

<form method="post" action="/">
            <input type="hidden" name="_csrf" value="{{csrfToken}}">
            .
            .
</form>

您在表单中插入密码和用户名。

app.js

   var express = require('express');
var helmet = require('helmet');
var csrf = require('csurf');
var path = require('path');
var favicon = require('serve-favicon');
var flash = require('connect-flash');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');


var routes = require('./routes/index');
var users = require('./routes/users');
var profile = require('./routes/profile');

var app = express();


// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));

app.use(logger('dev'));

//Security shyts

app.use(helmet());
app.use(helmet.xssFilter({ setOnOldIE: true }));
app.use(helmet.frameguard('deny'));
app.use(helmet.hsts({maxAge: 7776000000, includeSubdomains: true}));
app.use(helmet.hidePoweredBy());
app.use(helmet.ieNoOpen());
app.use(helmet.noSniff());
app.use(helmet.noCache());

// rest of USE
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({secret: 'anystringoftext', saveUninitialized: true, resave: true, httpOnly: true, secure: true}));
app.use(csrf()); // Security, has to be after cookie and session.
app.use(flash());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
app.use('/profile', profile);


// catch 404 and forward to error handler

app.use(function (req, res, next) {
  res.cookie('XSRF-TOKEN', req.csrfToken());
  res.locals.csrftoken = req.csrfToken();
  next();
})

//app.use(function(req, res, next) {
//  var err = new Error('Not Found');
//  err.status = 404;
//  next(err);
//});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});


module.exports = app; 

我在会话和cookie解析器之后放了csrf。

index.js

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'some title',message: '' });
});

router.post('/',function(req,res){
// Where I have a bunch of mysql queries to check passwords and usernames where as if they succeed they get:
res.redirect('profile');
// Else:
res.redirect('/');
 });

提交表单后我得到的是,无论是否插入正确的用户名和密码,我仍然会收到同样的错误:

invalid csrf token

403

ForbiddenError: invalid csrf token

另外我想补充一点,我已经在节点上工作了大约2个星期,所以我可能还有很多需要学习的东西。

2 个答案:

答案 0 :(得分:5)

{{csrfToken}}不是EJS构造,因此它根本不会扩展,可能会直接发送到您的服务器。

这应该更好:

<input type="hidden" name="_csrf" value="<%= csrfToken %>">

中间件设置为csrftoken,小写't',模板需要大写'T':

res.locals.csrftoken = req.csrfToken(); // change to `res.locals.csrfToken`

您还会生成两个不同的令牌,这可能不是您想要的:

app.use(function (req, res, next) {
  var token = req.csrfToken();
  res.cookie('XSRF-TOKEN', token);
  res.locals.csrfToken = token;
  next();
});

最后,您可能必须将中间件移至路由声明之前,否则将不会被调用:

app.use(function (req, res, next) {
  var token = req.csrfToken();
  res.cookie('XSRF-TOKEN', token);
  res.locals.csrfToken = token;
  next();
});
app.use('/', routes);
app.use('/users', users);
app.use('/profile', profile);

答案 1 :(得分:2)

我的Express版本为 6.14.4 。最重要的事情是您必须保持行的顺序。 App.js

var cookieParser = require('cookie-parser');
var csrf = require('csurf');
var bodyParser = require('body-parser');

//order of bellow lins is very important
app.use(bodyParser.urlencoded({ extended: false }))
app.use(cookieParser())
app.use(csrf({ cookie: true }))

routes / index.js

var express = require('express');
var router = express.Router();

router.get('/user/signup', function(req, res, next){
  console.log("csruf: "+req.csrfToken());
  res.render('user/signup', { csrfToken: req.csrfToken() });
});

router.post('/postuser', function(req, res, next){
 //res.render('/');
 res.redirect('/');
});

查看文件

 <form action="/postuser"  method="POST">
            <div class="form-group">
                <label for="email"> E-Mail</label>
                <input type="text" id="email" name="email" class="form-control">
            </div>
            <div class="form-group">
                <label for="password">Password</label>
                <input type="password" id="password" name="password" class="form-control">
            </div>
            <input type="hidden" name="_csrf" value="{{csrfToken}}">
            <button type="submit" class="btn btn-primary">Sign Up</button>
   </form>