Reputation: 59576
I am trying to enable the csrf module of Express 4 in an existing application.
I have added the following code:
var csrf = require('csurf')
...
app.use(csrf());
I have started my application and I get:
Error: misconfigured csrf
and a stack trace. Nothing else.
I have checked the documentation, but it is unclear. Can someone help? What is the minimum configuration required to use this module?
Upvotes: 25
Views: 28053
Reputation: 11
// ALWAYS USE AFTER THE SESSION CONFIG as like
const express = require('express');
const session = require('express-session');
const csurf = require('csurf')
const app = express()
app.use(session({
secret: "your secret string. you can also save it in .env file",
cookie: {},
resave: false,
saveUninitialized: false
}));
// then use the csurf() middleware
app.use(csurf());
Upvotes: 1
Reputation: 1099
If declaring csurf
below cookieParser
still throws an error, try to add these inside csurf
.
app.use(cookieParser());
app.use(csurf({ cookie: true }));
Upvotes: 0
Reputation: 125
Step1: Install express-session and cookie-parser
npm i express-session
npm i -D @types/express-session
npm i cookie-parser
npm i -D @types/cookie-parser
Step 2: In your main.ts file in your nest js project add the following lines of code
app.use(cookieParser());
app.use(
session({
secret: 'your-secret',
resave: false,
saveUninitialized: false,
}),
);
app.use(csurf());
see the following cookie and session links for more details
Upvotes: 0
Reputation: 382
app.use(
sessions({
cookieName: 'demo-session',
secret: 'this is a secret msg',
duration: 30 * 60 * 1000,
})
);
app.use(csurf({ sessionKey: 'demo-session' }));
I got the same error when the sessionKey was not the same in the session middleware and csurf. csurf uses session as default sessionKey if not provided. Here the sessionKey is demo-session, which should be the same in your session middleware.
Upvotes: 0
Reputation: 2044
If you're using Redis as a session store and the server isn't running, you will also get a misconfigured error.
https://github.com/expressjs/csurf/issues/73
Upvotes: 15
Reputation: 59576
I have found the solution. The call to app.use(csrf())
must be set after app.use(cookieParser())
AND app.use(session({...})
.
Upvotes: 67