ForbiddenError:在执行post方法express js时无效的csrf令牌

时间:2021-03-06 05:07:39

标签: javascript node.js express session cookies

我是表达 js 的新手,我正在从 firebase admin sdk 制作身份验证系统,我使用 csurf 来确保安全,但是每当我尝试向 "/api/music/like" 发送 post 请求时,它都会引发错误 ForbiddenError: invalid csrf token 你能帮我调试一下吗。

import cookieParser from "cookie-parser"
import csrf from 'csurf';
const app = express();

const __dirname = dirname(fileURLToPath(import.meta.url));
const csrfMiddleware = csrf({cookie: true})
app.use(cors())
app.use(bodyParser.urlencoded({extended : true, limit: "100mb"}));
app.use(express.static(path.join('build')))
app.use(bodyParser.json({limit: '100mb'}));
app.use(cookieParser())
app.use(csrfMiddleware)
app.use(fileupload())
app.all("*", (req, res, next)=>{
    res.cookie("XSRF-TOKEN", req.csrfToken());
    next();
})

const db = admin.database()

//routes

const server = app.listen(process.env.PORT || 4000, () => console.log("listening at port 4000..."))

const io = new socketio.Server(server)
let id;
io.on('connection', socket=>{
    id = socket.handshake.query.id
    if(id != "null"){
        socket.join(id)
        io.to(id).emit("message", {
            "name": id
        })
    }
})









app.io = io







app.post("/api/login", (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("UNAUTHORIZED REQUEST!")
        }
    )
})

app.get("/signout", (req, res)=>{
    //res.send({"signedout": true})
    res.clearCookie("session")
    res.end("success")
})


app.use((req, res, next)=>{
    const token = req.cookies.session||"";
    admin.auth().verifySessionCookie(token)
    .then(()=>next())
    .catch((err)=>{
        // res.send({"signedout": true})
    })
})

app.use("*", (req, res, next)=>{
    const token = req.cookies.session
    admin.auth().verifySessionCookie(token, true)
    .then((decodedToken)=>{
        app.uid = decodedToken.uid
        next()
    })
    .catch((err)=>console.log(err))
})



app.use("/api/music/upload", upload)
app.use("/api/home/trending", trendingRoute)
app.use("/api/home/result", resultRoute)
app.use("/api/home/popular", popularRoute)
app.use("/api/home/recomended", recomendRoute)
app.use("/api/u/musics", userMusicsRoute)
app.use("/api/music/like", likeRoute)//problem occurs here
app.use("/api/home/liked", userLikes)
app.use("/api/listen", listen)
app.use("/api/u/notification", notifications)

0 个答案:

没有答案