Express.js csrf"配置错误的csrf"错误

时间:2016-01-01 17:16:40

标签: express csrf

我创建了一个新的Express应用程序(4.13.1)并没有添加任何东西。我试着让它与Angular一起使用,但我一开始就陷入困境。

我现在正在使用express-jwt(cookies)处理身份验证,所以我不处理会话(在Redis,Mongo等中存储会话)或其他东西。

以下是我添加到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();
});

当我访问localhost:3000时,我收到上述错误。

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)

2 个答案:

答案 0 :(得分:0)

您不应该return next();

试试next();

答案 1 :(得分:0)

下面的代码对我有用。如果你仍然面临问题,请告诉我。

如前所述,您没有使用Sessions,您可以让csurf知道您正在使用Cookie来设置CSRF令牌。

第1步:配置

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);

步骤2: 在路线中,

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

步骤3:在HTML中为csrf令牌添加隐藏字段 示例:

<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>