title: Bad CSRF token with AngularJS and Express
body: <p>I would like to add a CSRF protection in my app which uses a MEAN stack.</p>
  
  <p>I tried the answer already given by someone : <a href="https://stackoverflow.com/questions/19566949/csrf-protection-in-expressjs/22984309#22984309">CSRF Protection in ExpressJS</a></p>
  
  <p>But it was for the older express version, so I made some changes :</p>
  
  <pre><code>app.use(cookieParser(config.cookieSecret, { httpOnly: true }));
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({ extended: false }));
  app.use(session({ secret: config.sessionSecret, resave: false, saveUninitialized: true }));
  app.use(passport.initialize());
  app.use(passport.session());
  app.use(flash());
  app.use(csrf({value: function(req) {
          var token = (req.body &amp;&amp; req.body._csrf)
              || (req.query &amp;&amp; req.query._csrf)
              || (req.headers['x-csrf-token'])
              || (req.headers['x-xsrf-token']);
          return token;
      }
  }));
  app.use(function(req, res, next) {
    res.cookie('XSRF-TOKEN', req.csrfToken());
    next();
  });
  </code></pre>
  
  <p>I can see the token named <code>XSRF-TOKEN</code> is well generated on my app (using Chrome inspection).</p>
  
  <p>But when I post a form (Angular frontend), I have an error about the token :</p>
  
  <p><code>{"message":"invalid csrf token","error":{"expose":true,"code":"EBADCSRFTOKEN","statusCode":403,"status":403}}</code></p>
  
  <p>Did I miss something ? I'm wondering if <code>req.csrfToken()</code> generates the good token given by Angular...</p>
  
  <p><strong>EDIT :</strong></p>
  
  <p>I just see the <code>XSRF-TOKEN</code> is used by AngularJS in <code>$http</code> requests <strong>only</strong>. So I think I have to add a hidden input in my form to post with csrf value, to be checked by Express, but how ?</p>