我在使用 csurf 时遇到问题,当我对用户进行身份验证时,我设置了一个 cookie,他被重定向到管理页面,他可以访问带有表单的页面来注册一些数据,但是当我发送 POST 数据时为了保存在我的数据库中,它返回给我这个错误:ForbiddenError: invalid csrf token
我正在使用 sequelize,所以 app.post 有一些控制器来存储数据。另外,我没有使用我的数据库对用户进行身份验证,而是使用了 firebase,登录工作正常,只是当我将其他数据发送到 db 时,它返回错误
APP.JS
const cookieParser = require("cookie-parser");logado
const csrf = require("csurf");
const bodyParser = require("body-parser");
const admin = require("firebase-admin");
const express = require("express");
const hbs = require('express-handlebars');
const serviceAccount = require("../serviceAccountKey.json");
const SocioController = require("./controllers/SocioController");
require('./database');
const csrfMiddleware = csrf( {cookie: true} );
var db = admin.database();
const PORT = process.env.PORTS || 8080;
const app = express();
//config
//Sessão Login
app.use(express.json());
app.use(cookieParser());
app.use(csrfMiddleware);
app.set('view engine', 'hbs')
app.engine('hbs', hbs({
defaultLayout: 'main',
extname: 'hbs',
defaultView: 'main',
layoutsDir: __dirname + '/views/layout',
partialsDir: __dirname + '/views/partials'
}));
app.use(express.static('public'))
app.use('/css', express.static(__dirname + '/public/css'));
app.use('/fonts', express.static(__dirname + '/public/fonts'));
app.use('/img', express.static(__dirname + '/public/img'));
app.use('/js', express.static(__dirname + '/public/js'));
app.use('/plugins', express.static(__dirname + '/plugins'));
app.all("*", (req, res, next) => {
res.cookie("XSRF-TOKEN", req.csrfToken());
next();
});
app.get("/", function(req, res){
res.render('login',{
layout: 'main',
template: 'hold-transition login-page container-fluid',
});
});
app.get("/login", function(req, res){
res.render('login',{
layout: 'main',
template: 'hold-transition login-page container-fluid',
});
});
app.get("/userPage", function (req, res) {
const sessionCookie = req.cookies.session || "";
admin
.auth()
.verifySessionCookie(sessionCookie, true /** checkRevoked */)
.then((user) => {
var ref = db.ref("users/" + user.uid);
ref.on('value', (data)=>{
if(data.val().funcao == 'adm'){
res.render('adm', {
isAdm: true,
layout: 'userspages',
template: 'hold-transition sidebar-mini layout-fixed',
username: data.val().nome,
userimage: "img/avatar2.png",
});
}else if(data.val().funcao=='lojista'){
res.render('lojista', {
isAdm: false,
layout: 'userspages',
template: 'hold-transition sidebar-mini layout-fixed',
username: data.val().nome,
userimage: "img/avatar2.png",
});
}else{
alert("Usuário não cadastrado");
}
});
})
.catch((error) => {
res.redirect("/login");
});
});
app.get("/cadastroEmpresa", checkCookiesMiddleware ,function(req, res){
var ref = db.ref("users/" + req.decodeClaims.uid);
ref.on('value', (data)=>{
res.render('cadastrar-empresa', {
isAdm: true,
layout: 'userspages',
template: 'hold-transition sidebar-mini layout-fixed',
username: data.val().nome,
userimage: "img/avatar2.png"
});
});
});
app.post("/cadastrarSocio", checkCookiesMiddleware, SocioController.store);
app.post("/sessionLogin", (req, res) => {
const idToken = req.body.idToken.toString();
const expiresIn = 60 * 60 * 24 * 5 * 1000;
admin
.auth()
.createSessionCookie(idToken, { expiresIn })
.then(
(sessionCookie) => {
const options = { maxAge: expiresIn, httpOnly: true };
res.cookie("session", sessionCookie, options);
res.end(JSON.stringify({ status: "success" }));
},
(error) => {
res.status(401).send("Requisição Não Autorizada!");
}
);
});
function checkCookiesMiddleware (req, res, next){
const sessionCookie = req.cookies.session || "";
admin
.auth()
.verifySessionCookie(sessionCookie, true /** checkRevoked */)
.then((decodeClaims) => {
req.decodeClaims = decodeClaims;
next();
})
.catch((error) => {
res.redirect("/login");
});
}
app.get("/sessionLogout", (req, res) => {
res.clearCookie("session");
res.redirect("/login");
});
app.listen(PORT, () => {
console.log(`Listening on http://localhost:${PORT}`);
});