我在CSRF令牌方面遇到问题。当我提交表单时,XSRF- TOKEN正在生成一个新的表单,但是我想我正在生成两个不同的令牌,这有点困惑。还有一个名为的令牌_csrf,因此我在开发人员工具中看到了两个不同的cookie(XSRF- TOKEN和_csrf),_csrf发布后它们没有变化。
XSRF- TOKEN
_csrf
我想要做的是为每个帖子请求生成一个新令牌,并检查它是否有效。我知道为了安全起见应该这样做,但是我坚持了下来。
漫长的一天,我是Express和NodeJS的新手。
这是我当前的设置。
var express = require('express') , passport = require('passport') , flash = require('connect-flash') , utils = require('./utils') , csrf = require('csurf') // setup route middlewares ,csrfProtection = csrf({ cookie: true }) , methodOverride = require('method-override') , bodyParser = require("body-parser") , parseForm = bodyParser.urlencoded({ extended: false }) , cookieParser = require('cookie-parser') , cookieSession = require('cookie-session') , LocalStrategy = require('passport-local').Strategy , RememberMeStrategy = require('../..').Strategy; var app = express(); app.set('views', __dirname + '/views'); app.set('view engine', 'ejs'); app.engine('ejs', require('ejs-locals')); app.use(express.logger()); app.use(express.static(__dirname + '/../../public')); app.use(cookieParser()); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); app.use(methodOverride()); app.use(express.session({ secret: 'keyboard cat' })); app.use(flash()); // Initialize Passport! Also use passport.session() middleware, to support // persistent login sessions (recommended). app.use(passport.initialize()); app.use(passport.session()); app.use(passport.authenticate('remember-me')); app.use(app.router); app.use(csrf()); app.use(function (req, res, next) { res.cookie('XSRF-TOKEN', req.csrfToken()); res.locals.csrftoken = req.csrfToken(); next(); });
路线
app.get('/form', csrfProtection, function(req, res) { // pass the csrfToken to the view res.render('send', { csrfToken: req.csrfToken()}); }); app.post('/process', parseForm, csrfProtection, function(req, res) { res.send('data is being processed'); });
send.ejs(/表格GET)
<form action="/process" method="POST"> <input type="hidden" name="_csrf" value="<%= csrfToken %>"> Favorite color: <input type="text" name="favoriteColor"> <button type="submit">Submit</button> </form>
根据您共享的代码量,有些事情看起来不正确:
1。您可能需要交换这些行,以便csrf在路由之前运行。
app.use(app.router); app.use(csrf());
2。这些线需要放置在路线之前。
app.use(csrf()); app.use(function (req, res, next) { res.cookie('XSRF-TOKEN', req.csrfToken()); res.locals.csrftoken = req.csrfToken(); next(); }); app.use(app.router);
3。locals.csrftoken以您的形式使用
locals.csrftoken
<form action="/process" method="POST"> <input type="hidden" name="_csrf" value="<%= csrftoken %>"> Favorite color: <input type="text" name="favoriteColor"> <button type="submit">Submit</button> </form>