简体   繁体   中英

Express.js csrf “misconfigured csrf” error

I created a new Express app (4.13.1) and didn't add anything. I'll try to make it work with Angular, but I stuck in the first place.

I'm handling authentication using express-jwt (cookies) for now, so I'm not dealing with sessions (storing sessions in Redis, Mongo, etc) or something.

Here's what I've added to my app.js.

var csrf = require('csurf');

app.use(cookieParser('randomStringisHere222'));
app.use(csrf());
app.use(function(req, res, next) {
  res.cookie('XSRF-TOKEN', req.csrfToken());
  return next();
});

When I visit localhost:3000 , I get the error above.

misconfigured csrf

Error: misconfigured csrf
    at getsecret (/Users/itsme/Desktop/k/node_modules/csurf/index.js:195:11)
    at csrf (/Users/itsme/Desktop/k/node_modules/csurf/index.js:60:18)
    at Layer.handle [as handle_request] (/Users/itsme/Desktop/k/node_modules/express/lib/router/layer.js:95:5)
    at trim_prefix (/Users/itsme/Desktop/k/node_modules/express/lib/router/index.js:312:13)
    at /Users/itsme/Desktop/k/node_modules/express/lib/router/index.js:280:7
    at Function.process_params (/Users/itsme/Desktop/k/node_modules/express/lib/router/index.js:330:12)
    at next (/Users/itsme/Desktop/k/node_modules/express/lib/router/index.js:271:10)
    at cookieParser (/Users/itsme/Desktop/k/node_modules/cookie-parser/index.js:48:5)
    at Layer.handle [as handle_request] (/Users/itsme/Desktop/k/node_modules/express/lib/router/layer.js:95:5)
    at trim_prefix (/Users/itsme/Desktop/k/node_modules/express/lib/router/index.js:312:13)

You shouldn't have to return next();

Just try next();

Below code is working for me. Let me know in case you still face issue.

As mentioned that you are not using Sessions, you have make csurf aware that you are using cookies for setting the CSRF token.

Step1: Configuration

var csrf = require('csurf');
var cookieparser= require('cookie-parser'); 

//cookieparser must be placed before csrf 
app.use(bodyparser.urlencoded({extended:false}));
app.use(cookieParser('randomStringisHere222'));
app.use(csrf({cookie:{key:XSRF-TOKEN,path:'/'}}));

//add the your app routes here
app.use("/api", person);
app.use("/", home);

Step2: In the route,

res.render('myViewPage',{csrfTokenFromServer:req.csrfToken()}); 

Step3: Include a hidden field in the HTML for csrf token Example:

<form action="/api/person" method="POST">
      <input type="hidden" name="_csrf" value=<%=csrfTokenFromServer %> />
      First name:<br>
      <input type="text" name="firstname" value="">
      <br>
      Last name:<br>
      <input type="text" name="lastname" value="">
      <br><br>
      <input type="submit" value="Submit">
 </form>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM