Express.js csrf “misconfigured csrf” error

我的未来我决定 提交于 2019-12-08 13:41:19

问题


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)

回答1:


You shouldn't have to return next();

Just try next();




回答2:


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>


来源:https://stackoverflow.com/questions/34558224/express-js-csrf-misconfigured-csrf-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!