Reputation: 7318
I read many post on the topic but none seem to help the error message "ForbiddenError: invalid csrf token" I get.
As you can see from the entry app.js file below, I set the csrf value in session and then I can use it in the template:
import * as express from "express"
import users from "./src/users/boundaries-users/users-boundaries"
import * as directory from "./src/directory/boudaries-directory/links-boudaries"
import * as comment from "./src/comments/boundaries-comments/comments-boundaries"
import admin from "./src/@admin/boundaries-admin/admin-boundaries"
import * as session from "express-session"
import Home from "./src/home/use-cases-home/home-case"
import * as email from "./src/utilities-global/email"
import * as csrf from "csurf"
let nodemailer = require( "nodemailer" )
let app = express()
/** Session */
app.use( session( { "secret": "taracebulba" } ) )
/*
Middleware used to allow template system to acces session information. Must be placed between session and routes middlewares.
http://expressjs.com/fr/api.html#res.locals and
http://stackoverflow.com/questions/16823008/express-res-locals-somevariable-use-in-hbs-handlebars-template
*/
app.use( function( req, res, next ) {
res.locals.session = req.session
next()
} )
app.use( csrf() )
app.use( function( req, res, next ) {
res.locals._csrf = req.csrfToken()
next()
} )
// Console log sessions
app.use( function( req, res, next ) {
console.log( req.session)
next()
} )
/* ---------------------------------------------------------------------------------------------------------------*/
// Home url handling
/* ---------------------------------------------------------------------------------------------------------------*/
// Home
app.get( "/", ( req, res ) => {
const url = "/"
new Home( req, res ).homeDisplay( undefined, undefined, undefined, "isHome", url )
} )
// Home searched
app.get( "/from/:source/to/:target/:sorting", ( req, res ) => {
const sourceLanguage = req.params.source
const targetLanguage = req.params.target
const sorting = req.params.sorting
const url = req.url
new Home( req, res ).homeDisplay( sourceLanguage, targetLanguage, sorting, "isNotHome", url )
} )
// Contact
app.get( "/contact", ( req, res ) => {
res.render( "contact.ejs", {
"data": {
"pageTitle": "Contact us"
}
} )
} )
/* ---------------------------------------------------------------------------------------------------------------*/
// Routes
/* ---------------------------------------------------------------------------------------------------------------*/
app.use( "/users", users )
app.use( "/directory", directory.routerDirectory )
app.use( "/comment", comment.routerComments )
app.use( "/admin", admin )
/** Views */
app.set( "views", [
__dirname + "/src/users/views-users",
__dirname + "/src/directory/views-directory",
__dirname + "/src/comments/views-comments",
__dirname + "/src/views-global",
__dirname + "/src/@admin/views-admin",
__dirname + "/src/home/views-home"
] )
app.set( "view engine", "ejs" )
app.locals.moment = require( "moment" )
/** Static */
app.use( express.static( __dirname + "/src/@frontend" ) )
/** Handle uncought exception */
process.on( "uncaughtException", function( er ) {
const transporter = nodemailer.createTransport( email.smtpConfig )
console.error( er.stack ) // [3]
transporter.sendMail( {
"from" : "[email protected]",
"to" : "******@gmail.com",
"subject": er.message,
"text" : er.stack
}, function( er ) {
if ( er ) {
console.error( er )
}
process.exit( 1 )
} )
} )
app.listen( 3000, function() {
console.log( "Example app listening on port 3000!" )
} )
I checked the session and the csrfsecret key is there:
Session {
cookie:
{ path: '/',
_expires: null,
originalMaxAge: null,
httpOnly: true },
csrfSecret: 'JcR1li3zf5bFXZg7fcYQbrz4' }
also, in the template generated I see the token correctly:
<form action="/directory/create" method="post">
<input name="_csrf" value="zN2jALCJ-K2cXntALNBMC9jfioHDuUJmpUks" type="hidden">
So if the data is in session, and html has the csrf value as a hidden field, then why this doesn't work ? Is it because my app uses multiples routes paths ?
Upvotes: 0
Views: 2381
Reputation: 7318
The answer from "Ben Fortune" got me in the right direction: the system was not able to parse the form without bodyParser to check for the submitted token value.
Adding bodyParser solved the token issue, but introduced a new problem down the road with a conflict with another form parser I was using not as middleware, but locally: Formidable.
Solution:
I removed bodyParser middleware completely and kept my Formidable form processing as is. But, on the template containing form, I added the token not as a hidden input, which would not be recognized, but as a query string:
<form action="/directory/create?_csrf=<%= _csrf %>" method="post">
This solves the issue.
Upvotes: 0
Reputation: 32117
From the looks of it, you aren't using body-parser, which is required to parse the form to get the csrf token.
Install the package
npm install --save body-parser
And require the package and add it to your middleware before csurf.
import bodyParser from 'body-parser';
app.use(bodyParser.urlencoded({
extended: true
}));
Upvotes: 3