gpt4 book ai didi

node.js - Node JS/Angular 2 应用程序,ForbiddenError : invalid csrf token

转载 作者:太空狗 更新时间:2023-10-29 19:34:57 27 4
gpt4 key购买 nike

我正在开发示例应用程序,在服务器端使用 Node.js,在前端使用 Angular 2。

为了防止 CSRF 攻击,我使用了“csurf”中间件下面是设置中间件的相关代码

// cookie parser
app.use(cookieParser());

// express session middleware , this should be after cookie parser
app.use(session({secret:'clickclick'}));

app.use(session({
secret: 'clickclick',
cookie: {
path:'/',
httpOnly:true,
maxAge:null
}
}));

// CSRF middleware
app.use(csurf());

在 node.js 路由下面设置“_csrf” header

router.get('/:id/products/:pid' ,  wrap(function *(req , res , next) {

try
{
console.log('url' , req.url);
res.setHeader('_csrf', req.csrfToken());
let product = yield category.getProduct(req , res , next);
res.send(product);
}
catch(err)
{
res.status(500).send(err);
}

}))

上面提到的路由 '/:id/products/:pid' 是从我下面的 Angular 2 服务方法调用的

// Get Product
GetProduct(id:string, pid:string):Observable<Product> {

return this.http.get('./categories/' + id + '/products/' + pid)
.map(data =>{ let headers:Headers = data.headers;
this.csrfToken = headers.get('_csrf') ;
return data.json() })
.catch(this.handleError);
}

此方法将从服务器返回的 _csrf header 分配给“this.csrfToken”属性。

当下面的服务方法发出 AJAX POST 请求时,它使用上面方法设置的“this.csrfToken”属性值并设置 header “_csrf”值。

// Add an item to cart
AddTocart(product:Product)
{
let item = { pid:product._id , name:product.name , price:product.price , qty:1 , total:product.price };
//this.cart.push(item);

// make an AJAX call to save the item in server session
let url = './cart/add';
let headers = new Headers({'Content-Type':'application/json' , '_csrf':this.csrfToken});
let requestOptions = new RequestOptions({headers:headers});

this.http.post(url , item , requestOptions)
.map(data => {
this.cart.push(item);
}
)
.catch(this.handleError)
.subscribe( data => { });

}

下面是GetProduct服务方法的Response Header。 enter image description here

下面是“AddTocart”服务方法的请求头。

enter image description here

知道是什么导致了“ForbiddenError:无效的 csrf token ”错误。如果我需要提供更多信息或提供的信息不清楚,请告诉我。

最佳答案

我知道这是一个较旧的问题,但我将其添加到此处以防将来有人偶然发现它。在类似的项目上工作并遇到相同的错误,我通过在 POST 请求中添加 XSRF-TOKEN header 来修复它,其值取自 $.cookie("XSRF-TOKEN")(使用 jquery 和 cookies 插件)。根据文档,_csrf 也应该可以工作。

来自 the project page :

The default value is a function that reads the token from the following locations, in order:

req.body._csrf - typically generated by the body-parser module.
req.query._csrf - a built-in from Express.js to read from the URL query string.
req.headers['csrf-token'] - the CSRF-Token HTTP request header.
req.headers['xsrf-token'] - the XSRF-Token HTTP request header.
req.headers['x-csrf-token'] - the X-CSRF-Token HTTP request header.
req.headers['x-xsrf-token'] - the X-XSRF-Token HTTP request header.

据我所知,错误似乎来自包含正确 cookie 的 POST/PUT 请求,但 nodejs/csurf 并没有在那里寻找它们。

在您的特定情况下,_csrf 应该与购物车项目一起在请求正文中,或者 header 应该重命名为 csrf-token,或者其他选项。

关于node.js - Node JS/Angular 2 应用程序,ForbiddenError : invalid csrf token,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41510384/

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