gpt4 book ai didi

javascript - 在 NodeJS 中使用 CSRF

转载 作者:搜寻专家 更新时间:2023-10-31 23:41:29 26 4
gpt4 key购买 nike


我正在尝试在我的 NodeJS 应用程序中使用 csrf。你可以看到下面的代码。当我运行这段代码时,出现“TypeError: req.csrfToken is not a function”错误。

我想为所有请求创建 csrf token ,并想在 ajax 调用中检查 csrf token 。正如我所说,我无法创建 csrf token ,我遇到了错误。另外如何在 ajax 调用中检查 csrf token ?

你能帮帮我吗?
谢谢

服务器端:

var express = require('express');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var csrf = require('csurf');
var bodyParser = require('body-parser');

/*this line commented*/
//var csrfProtection = csrf({ cookie: false });
var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

var parseForm = bodyParser.urlencoded({ extended: false });
app.use(cookieParser());

/*this line added*/
app.use(csrf({ cookie: false }));

app.use(session({
genid: function (req) {
return "lkgktktgjknvfndkj-dfgjnkdfkjgn-dfgdfg";
},
name: "mySecret",
resave: false, // don't save session if unmodified
saveUninitialized: false, // don't create session until something stored
secret: 'thisIsASecret'
}));

app.use(express.static(path.join(__dirname, 'public')));

app.use(function (req, res, next) {
res.locals.csrfToken = req.csrfToken();

next();
});

app.get('/', /*csrfProtection,*/ function (req, res) {
res.render('index')
});

app.post('/process', parseForm, /*csrfProtection,*/ function (req, res) {
res.send('data is being processed')
});

索引.jade

meta(name="csrf-token", content="#{csrfToken}")
block content
input(type="hidden" name="_csrf" value="#{csrfToken}")

|Favorite color: <input type="text" name="favoriteColor">
button(type="submit" id="sbmt") Submit

script(src= "/javascripts/jquery-2.2.1.js")

script.
$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
var token;
if (!options.crossDomain) {
token = $('meta[name="csrf-token"]').attr('content');
if (token) {
return jqXHR.setRequestHeader('X-CSRF-Token', token);
}
}
});

$("#sbmt").click(function (e) {
e.preventDefault();
$.post(
"/process",
{
//text: text,
_csrf : $('meta[name="csrf-token"]').attr('content')
}, function (data) {
console.log(data);
});
});

最佳答案

你必须添加:

app.use(session({ ... });
// Add this after session
app.use(csrfProtection);

您需要按照说明在 session 之后添加 here :

If you are setting the "cookie" option to a non-false value, then you must use cookie-parser before this module. Otherwise, you must use a session middleware before this module. For example: express-session cookie-session

关于javascript - 在 NodeJS 中使用 CSRF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36442919/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com