Avoid CSRF in Express

260 views
Skip to first unread message

alexri...@gmail.com

unread,
Sep 30, 2016, 7:41:54 AM9/30/16
to Express

I am fairly new to Express! I have wrote a code to avoid csrf but something is wrong and I always get the error of invalid csrf token. Can anybody help me? This the code of my express file:

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


var csrfProtection = csrf({ cookie: true })

// Create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })

var app = express();

app.use(cookieParser())

app.use(express.static('public'));
app.get('/index.html', csrfProtection, function (req, res) {
  res.render('send', { csrfToken: req.csrfToken() });
})

app.post('/process_post', urlencodedParser, csrfProtection, function (req, res) {
   // Prepare output in JSON format
   response = {
      first_name:req.body.first_name,
      last_name:req.body.last_name
   };
   console.log(response);
   res.end(JSON.stringify(response));
})



var server = app.listen(8081, 'localhost', function () {
   var host = server.address().address
   var port = server.address().port

   console.log("Example app listening at http://%s:%s", host, port)

and this is the code of my html file:


 <form action = "http://127.0.0.1:8081/process_post" method = "POST">
 <input type="hidden" name="_csrf" value="<%=csrfToken%>">
     First Name: <input type = "text" name = "first_name"> <br>
     Last Name: <input type = "text" name = "last_name">
     <input type = "submit" value = "Submit">
  </form>


I think there is something regarding setting the token in hidden value because when i try to see the source code of the page in browser the value is still <%=csrfToken%> while it should be set to a random value.


I would be thankful if you can give me some hints!

Jason Crawford

unread,
Sep 30, 2016, 7:46:05 PM9/30/16
to expre...@googlegroups.com
Sounds like your HTML file is not getting rendered by a templating engine. You need to name it something like send.html.ejs, and make sure EJS or whatever engine you want to use is included and configured:


Hope that helps,
Jason

--
You received this message because you are subscribed to the Google Groups "Express" group.
To unsubscribe from this group and stop receiving emails from it, send an email to express-js+unsubscribe@googlegroups.com.
To post to this group, send email to expre...@googlegroups.com.
Visit this group at https://groups.google.com/group/express-js.
For more options, visit https://groups.google.com/d/optout.



--
Fieldbook: Create a database, as easily as a spreadsheet
Reply all
Reply to author
Forward
0 new messages