Express.js csrf“;配置错误的csrf“;错误
我创建了一个新的Express应用程序(4.13.1),没有添加任何内容。我会尽量让它与Angular一起工作,但我首先卡住了 我现在正在使用ExpressJWT(cookies)处理身份验证,所以我不处理会话(在Redis、Mongo等中存储会话)或其他什么 以下是我在app.js中添加的内容Express.js csrf“;配置错误的csrf“;错误,express,csrf,Express,Csrf,我创建了一个新的Express应用程序(4.13.1),没有添加任何内容。我会尽量让它与Angular一起工作,但我首先卡住了 我现在正在使用ExpressJWT(cookies)处理身份验证,所以我不处理会话(在Redis、Mongo等中存储会话)或其他什么 以下是我在app.js中添加的内容 var csrf = require('csurf'); app.use(cookieParser('randomStringisHere222')); app.use(csrf()); app.us
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)
您不必
返回next()代码>
只要试试next()代码>下面的代码适用于我。让我知道,以防你们仍然面临这个问题
如前所述,您没有使用会话,您已经让csurf知道您正在使用cookies来设置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>
名字:
姓氏:
尝试移动app.use(csrf())代码>在所有其他应用程序之后发送。使用(…)
声明。这可能会有所帮助吗?