title: Trouble with Express 4 and CSRF Token posting
body: <p>I think I'm misunderstanding how the token is supposed to post. I'm just getting a 403 every time, even though it's actually attempting to pass the token. </p>
  
  <p>Here's the server code</p>
  
  <pre><code>var express = require('express');
  var path = require('path');
  var favicon = require('serve-favicon');
  var logger = require('morgan');
  var cookieParser = require('cookie-parser');
  var bodyParser = require('body-parser');
  var redis = require('redis');
  var session = require('express-session');
  var RedisStore = require('connect-redis')(session);
  var ejs = require('ejs');
  var csrf = require('csurf');
  var util = require('./public/javascripts/utilities');
  
  var routes = require('./routes/index');
  var users = require('./routes/users');
  var login = require('./routes/login');
  var loginProcess =     require('./public/javascripts/login.js').loginProcess;
  // var loginProcess = require('./public/javascripts/login.js')
  
  var client = redis.createClient();
  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'));
  app.use(express.static(path.join(__dirname, '/public')));
  app.use(cookieParser('secret'));
  app.use(session(
    {
      store: new RedisStore({ host: 'localhost', port: 6379, client:     client }),
      secret: 'secret',
      saveUninitialized: true,
      resave: false
    }
  ));
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({ extended: false }));
  app.use(csrf());
  app.use(util.csrf);
  app.use(util.authenticated);
  
  app.use('/', routes);
  app.use('/users', users);
  app.use('/login',
    login,
    loginProcess);
  
  
  // catch 404 and forward to error handler
  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;
  </code></pre>
  
  <p>The login route is </p>
  
  <pre><code>var express = require('express');
  var router = express.Router();
  
  router.get('/', function(req, res, next) {
    res.render('login', {title: 'Login'});
    next();
  });
  </code></pre>
  
  <p>Here is what I've got in var util</p>
  
  <pre><code>module.exports.csrf = function csrf(req, res, next){
    res.locals.csrftoken = req.csrfToken();
    next();
  };
  </code></pre>
  
  <p>I'm also using ejs, and have this after my form method='post'</p>
  
  <pre><code>&lt;input type="hidden" name="_csrf" value="&lt;%= csrfToken %&gt;&gt;"
  </code></pre>
  
  <p>Whenever it returns 403, the form data is at least getting the name of the input</p>
  
  <p>_csrf:</p>
  
  <p>username:Test</p>
  
  <p>password:>9000</p>
  
  <p>But as you can see, it's blank</p>
  
  <p>I also wasn't sure if the res.locals.csrftoken was being passed to the login route, so I also tried adding it directly there with a router.post, but got this error</p>
  
  <p>Error: Can't set headers after they are sent.</p>
  
  <p>I've gone through nearly every post concerning this I could find. I'm either not making the logical connection for what I'm missing, or am wholly misunderstanding something. Both are entirely plausible, my money is on the second one. Feel free to make any, why in the world are you doing that - that way - comments, because chances are I'm doing it out of ignorance, and those comments are good for the learning process. Thanks in advance. </p>
  
  <p><strong>edit</strong>: Removing my utility function and following correct 'csurf' docs successfully passed the csrf token to my /login view.</p>
  
  <p>I'm getting closer, still wrong, but this may shed some light as to where I'm getting confused.</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>var express = require('express');
  var router = express.Router();
  
  /* GET login listing. */
  router.get('/', function(req, res, next) {
    res.render('login', {title: 'Login', csrfToken: req.csrfToken() });
  });
  
  function loginProcess(req, res, next){
    console.log(req.body);
    res.send(req.body.username + ' ' + req.body.password);
    res.json(req.csrfToken());
    next();
  };
  
  router.post('/', loginProcess);
  
  module.exports = router;</code></pre>
  </div>
  </div>
  </p>
  
  <p><strike>Why would this redirect me to a 404 page?</strike>
  Because I didn't remove my authentication step before testing. </p>
  
  <p>Also, I know this is sending un &amp; pw in plain text along with the csrf token and that's no bueno. I'll get to that eventually. </p>
  
  <p>Something I did is attempting to set headers when submitting username and password. </p>
  
  <p>Error: Can't set headers after they are sent.</p>
  
  <p>I thought it was my loginProcess function, but removing next(), or adding res.end(); didn't help</p>
  
  <pre><code>function loginProcess(req, res, next){
    console.log(req.body);
    res.send(req.body.username + ' ' + req.body.password);
    res.json(req.csrfToken());
    res.end();
  };
  </code></pre>
  
  <p><strong>edit</strong> You can't use res.send and res.json like that because they're both technically sending, and you can't send headers+body and then send headers+body again.</p>
  
  <p>The token is automatically sent so I removed res.json(req.csrfToken();</p>
  
  <p>But somewhere I'm not redirecting correctly on post. I'm just getting a blank page with the username and passwords that were entered.  </p>
  
  <p><strong>edit:</strong> </p>
  
  <p>Hokay. So everything appears to be working properly. Here is the updated code. </p>
  
  <p>login.js</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>var express = require('express');
  var router = express.Router();
  
  /* GET login listing. */
  router.get('/', function(req, res, next) {
    res.render('login', {title: 'Login', csrfToken: req.csrfToken() });
  });
  
  function loginProcess(req, res, next){
    var isAuth = auth(req.body.username, req.body.password, req.session)
    if (isAuth){
      res.redirect('/chat');
    }else{
      res.redirect('/login');
    }
  };
  
  router.post('/', loginProcess);
  router.get('/logout', out);
  
  module.exports = router;</code></pre>
  </div>
  </div>
  </p>
  
  <p>app.js</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>var routes = require('./routes/index');
  var users = require('./routes/users');
  var login = require('./routes/login');
  var chat = require('./routes/chat');
  //var loginProcess = require('./public/javascripts/login.js').loginProcess;
  
  var client = redis.createClient();
  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'));
  app.use(express.static(path.join(__dirname, '/public')));
  app.use(cookieParser('secret'));
  app.use(session(
    {
      secret: 'secret',
      store: new RedisStore({ host: 'localhost', port: 6379, client: client }),
      saveUninitialized: true,
      resave: false
    }
  ));
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({ extended: false }));
  app.use(csrf({ cookie: true }));
  // app.use(util.csrf);
  app.use(util.authenticated);
  
  app.use('/', routes);
  app.use('/users', users);
  app.use('/login', login);
  app.use('/chat', [util.requireAuthentication], chat);</code></pre>
  </div>
  </div>
  </p>
  
  <p>I've still got a ton of cleanup, but it's at least functional.
  Much thanks to @Swaraj Giri</p>