简体   繁体   English

无法摆脱ForbiddenError:使用Csurf快递时无效的CSRF令牌

[英]Impossible to get rid of ForbiddenError: invalid csrf token on express with csurf

I read many post on the topic but none seem to help the error message "ForbiddenError: invalid csrf token" I get. 我读了很多关于该主题的文章,但似乎都没有帮助我收到错误消息“ ForbiddenError:invalid csrf token”。

As you can see from the entry app.js file below, I set the csrf value in session and then I can use it in the template: 从下面的入口app.js文件中可以看到,我在session中设置了csrf值,然后可以在模板中使用它:

import * as express from "express"
import users from "./src/users/boundaries-users/users-boundaries"
import * as directory from "./src/directory/boudaries-directory/links-boudaries"
import * as comment from "./src/comments/boundaries-comments/comments-boundaries"
import admin from "./src/@admin/boundaries-admin/admin-boundaries"
import * as session from "express-session"
import Home from "./src/home/use-cases-home/home-case"
import * as email from "./src/utilities-global/email"
import * as csrf from "csurf"
let nodemailer = require( "nodemailer" )

let app = express()

/** Session */
app.use( session( { "secret": "taracebulba" } ) )
/*
 Middleware used to allow template system to acces session information. Must be placed between session and routes middlewares.
 http://expressjs.com/fr/api.html#res.locals and
 http://stackoverflow.com/questions/16823008/express-res-locals-somevariable-use-in-hbs-handlebars-template
 */

app.use( function( req, res, next ) {
    res.locals.session = req.session
    next()
} )


app.use( csrf() )
app.use( function( req, res, next ) {
    res.locals._csrf = req.csrfToken()
    next()
} )


// Console log sessions
app.use( function( req, res, next ) {
    console.log( req.session)
    next()
} )


/* ---------------------------------------------------------------------------------------------------------------*/
// Home url handling
/* ---------------------------------------------------------------------------------------------------------------*/

// Home
app.get( "/", ( req, res ) => {
    const url = "/"

    new Home( req, res ).homeDisplay( undefined, undefined, undefined, "isHome", url )
} )

// Home searched
app.get( "/from/:source/to/:target/:sorting", ( req, res ) => {
    const sourceLanguage = req.params.source
    const targetLanguage = req.params.target
    const sorting        = req.params.sorting
    const url            = req.url

    new Home( req, res ).homeDisplay( sourceLanguage, targetLanguage, sorting, "isNotHome", url )
} )

// Contact
app.get( "/contact", ( req, res ) => {

    res.render( "contact.ejs", {
        "data": {
            "pageTitle": "Contact us"
        }
    } )
} )



/* ---------------------------------------------------------------------------------------------------------------*/
// Routes
/* ---------------------------------------------------------------------------------------------------------------*/
app.use( "/users", users )
app.use( "/directory", directory.routerDirectory )
app.use( "/comment", comment.routerComments )
app.use( "/admin", admin )




/** Views */
app.set( "views", [
    __dirname + "/src/users/views-users",
    __dirname + "/src/directory/views-directory",
    __dirname + "/src/comments/views-comments",
    __dirname + "/src/views-global",
    __dirname + "/src/@admin/views-admin",
    __dirname + "/src/home/views-home"
] )

app.set( "view engine", "ejs" )

app.locals.moment = require( "moment" )



/** Static */
app.use( express.static( __dirname + "/src/@frontend" ) )


/** Handle uncought exception  */
process.on( "uncaughtException", function( er ) {
    const transporter = nodemailer.createTransport( email.smtpConfig )
    console.error( er.stack ) // [3]
    transporter.sendMail( {
        "from"   : "alerts@mycompany.com",
        "to"     : "******@gmail.com",
        "subject": er.message,
        "text"   : er.stack
    }, function( er ) {
        if ( er ) {
            console.error( er )
        }
        process.exit( 1 )
    } )
} )

app.listen( 3000, function() {
    console.log( "Example app listening on port 3000!" )
} )

I checked the session and the csrfsecret key is there: 我检查了会话,并在其中找到了csrfsecret密钥:

  Session {
  cookie: 
   { path: '/',
     _expires: null,
     originalMaxAge: null,
     httpOnly: true },
  csrfSecret: 'JcR1li3zf5bFXZg7fcYQbrz4' }

also, in the template generated I see the token correctly: 另外,在生成的模板中,我可以正确看到令牌:

<form action="/directory/create" method="post">
     <input name="_csrf" value="zN2jALCJ-K2cXntALNBMC9jfioHDuUJmpUks" type="hidden">

So if the data is in session, and html has the csrf value as a hidden field, then why this doesn't work ? 因此,如果数据在会话中,并且html具有csrf值作为隐藏字段,那么为什么这不起作用? Is it because my app uses multiples routes paths ? 是因为我的应用程序使用了多个路由路径吗?

From the looks of it, you aren't using body-parser , which is required to parse the form to get the csrf token. 从外观上看,您并没有使用body-parser ,它是解析表单以获取csrf令牌所必需的。

Install the package 安装套件

npm install --save body-parser

And require the package and add it to your middleware before csurf. 并要求该软件包并将其添加到csurf 之前的中间件中。

import bodyParser from 'body-parser';

app.use(bodyParser.urlencoded({
  extended: true
}));

The answer from "Ben Fortune" got me in the right direction: the system was not able to parse the form without bodyParser to check for the submitted token value. 来自“ Ben Fortune”的答案使我朝了正确的方向:没有bodyParser,系统无法解析表单以检查提交的令牌值。

Adding bodyParser solved the token issue, but introduced a new problem down the road with a conflict with another form parser I was using not as middleware, but locally: Formidable. 添加bodyParser可以解决令牌问题,但随后又引入了一个新问题,即与我不是在中间件上而是在本地使用的另一个表单解析器冲突:强大。

Solution: 解:

I removed bodyParser middleware completely and kept my Formidable form processing as is. 我完全删除了bodyParser中间件,并保持了我的强大表单处理能力。 But, on the template containing form, I added the token not as a hidden input, which would not be recognized, but as a query string: 但是,在包含表单的模板上,我不是将令牌作为隐藏的输入(不会被识别,而是作为查询字符串)添加的:

<form action="/directory/create?_csrf=<%= _csrf %>" method="post">

This solves the issue. 这样就解决了问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM