仔细观察并尝试了我能在这里找到的所有东西,以及谷歌搜索的其他地方......我只是无法超越这个。我正在使用Node,Express,EJS,并尝试在表单上使用csurf,这是使用jQuery ajax发布的。无论我如何配置csurf,我得到" 403(禁止)无效的csrf令牌"
我尝试在app.js和控制器中全局配置。这是我在app.js中尝试的内容:
var express = require('express');
var session = require('express-session');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mysql = require('mysql');
var flash = require("connect-flash");
var csrf = require("csurf");
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(session({
secret: 'somethingsecret',
resave: true,
saveUninitialized: true,
httpOnly: true,
secure: false
}));
app.use(csrf());
app.use(function (req, res, next) {
var token = req.csrfToken();
res.cookie('XSRF-TOKEN', token);
res.locals.csrfToken = token;
console.log("csrf token = " + token);
next();
});
app.use(flash());
app.use(express.static(path.join(__dirname, 'public')));
app.use(function (err, req, res, next) {
if (err.code !== 'EBADCSRFTOKEN') return next(err);
// handle CSRF token errors here
res.status(403);
res.send('form tampered with');
})
//routing
var routes = require('./routes/index');
var users = require('./routes/users');
var register = require('./routes/register');
app.use('/', routes);
app.use('/users', users);
app.use('/register', register);
...使用此控制器:
var express = require("express");
var router = express.Router();
var bodyParser = require("body-parser");
var userSvc = require("../service/userservice");
var jsonParser = bodyParser.json();
router.get("/", function(req, res, next) {
console.log("token = " + token);
userSvc.getAllPublicRoles(function(data) {
res.render("register", {
title: "Register a new account",
roles: data
});
});
});
router.post("/new", jsonParser, function(req, res, next) {
userSvc.addUser(req.body, function(result) {
console.log("New user id = " + result.insertId);
res.send('{"success" : "Updated Successfully", "status" : 200}');
});
});
...而且这个观点:
形式:
<form id="registerForm" class="form-horizontal" method="post">
<input type="hidden" name="_csrf" value="<%= csrfToken %>" />
ajax电话:
$.ajax({
url: "/register/new",
type: "POST",
dataType: "json",
data: user
}).done(function(data) {
if (data) {
console.log("Success! = " + data);
}
}).fail(function(data) {
console.log("Something went wrong: " + data.responseText);
});
然后我只是尝试在控制器中执行所有操作,从app.js中删除所有引用,调用等,并使用与上面相同的表单和ajax调用:
var express = require("express");
var router = express.Router();
var bodyParser = require("body-parser");
var csrf = require("csurf");
var userSvc = require("../service/userservice");
var csrfProtection = csrf();
var jsonParser = bodyParser.json();
router.get("/", csrfProtection, function(req, res, next) {
var token = req.csrfToken();
console.log("token = " + token);
userSvc.getAllPublicRoles(function(data) {
res.render("register", {
title: "Register a new account",
csrfToken: token,
roles: data
});
});
});
router.post("/new", jsonParser, csrfProtection, function(req, res, next) {
userSvc.addUser(req.body, function(result) {
console.log("New user id = " + result.insertId);
res.send('{"success" : "Updated Successfully", "status" : 200}');
});
});
不知道从哪里开始。在闲暇时间,我一直在使用节点大约两个星期,所以请原谅我的无知。
答案 0 :(得分:5)
如果您想将令牌存储在cookie中而不是会话中,请让csurf为您创建cookie。
if(init())
{
return;
}
然后,当您通过POST数据使用AJAX进行呼叫时,或者作为自定义请求标头(例如'xsrf-token')时,您需要确保令牌可用。
此时,您正在向表单提供令牌,但不是实际请求(使用AJAX发送)。
例如,您可以在AJAX设置中呈现令牌:
// Store the token in a cookie called '_csrf'
app.use(csrf({cookie: true));
// Make the token available to all views
app.use(function (req, res, next){
res.locals._csrf = req.csrfToken();
next();
});
答案 1 :(得分:0)
经过几个小时的故障排除和搜索后,我找到了一个帮助回答它的帖子。我只需要在ajax帖子中传递标题值。有道理,我只是忽略了它。像这样:
<input type="hidden" id="_csrf" name="_csrf" value="<%= csrfToken %>" />
...然后在jQuery中:
$.ajaxSetup({
headers: {"X-CSRF-Token": $("#_csrf").val()}
});
答案 2 :(得分:0)
除了在邮件标题中添加“X-CSRF-Token”之外,您要完全禁用Cookie!
var csrfProtection = csurf({cookie:false});
作者在这里提到它 https://github.com/expressjs/csurf/issues/52
cookie和会话验证不应该合并 - 尽管它有点误导,因为他在他的文档中结合了cookie和会话验证: https://github.com/expressjs/csurf#simple-express-example
答案 3 :(得分:0)
我个人项目的另一种方法是在我成功提交表单时重新发送新令牌:
例如,在我的表单上(文件上传)我有以下html:
<form id="upload_form" type="multipart/form-data" data-csrf="{{csrfToken}}" method="post" action="/data_assets">
<input id="excell_upload" type="file" style="visible:hidden" name="data_assets"/>
</form>
在文件更改时,我会触发上传:
$('#excell_upload').on('change',function(event){
event.preventDefault();
var formData = new FormData($("#upload_form")[0]);
$.ajax({
'type':$("#upload_form").attr('method'),
'data': formData,
'url': $("#upload_form").attr('action'),
'processData': false,
'contentType': false,
'mimeType': 'multipart/form-data',
'headers': {"X-CSRF-Token": $("#upload_form").attr('data-csrf') },
'beforeSend': function (x) {
if (x && x.overrideMimeType) {
x.overrideMimeType("multipart/form-data");
}
$('#trigger_upload').addClass('disabled');
},
'success':function(data){
$('#upload_form').attr('data-csrf',data.csrfToken)
},
'fail':function(){
},
'complete':function(){
$('#trigger_upload').removeClass('disabled');
}
});
});
如您所知,我收到一个新的csrf令牌,以便能够重新使用我的表单进行新提交。我重新生成CSRF令牌:
app.post('/data_assets',function(req,res,next){
res.json({'csrfToken':req.csrfToken()});
});