如何调用使用EX press.js实现在阿贾克斯CSRF保护(寻求完整的例子)? [英] How to implement CSRF protection in Ajax calls using express.js (looking for complete example)?

查看:267
本文介绍了如何调用使用EX press.js实现在阿贾克斯CSRF保护(寻求完整的例子)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现在使用使用前press.js框架的Node.js内置的应用程序CSRF保护。该应用程序使得大量使用Ajax的后调用服务器。据我所知,连接框架提供CSRF中间件,但我不知道如何在客户端Ajax POST请求的范围执行。

I am trying to implement CSRF protection in an app built using node.js using the express.js framework. The app makes abundant use of Ajax post calls to the server. I understand that the connect framework provides CSRF middleware, but I am not sure how to implement it in the scope of client-side Ajax post requests.

有星星点点关于这张贴在这里的计算器等问题,但我还没有找到如何从客户端和服务器端实现它一个相当完整的例子。

There are bits and pieces about this in other Questions posted here in stackoverflow, but I have yet to find a reasonably complete example of how to implement it from both the client and server sides.

有没有人有他们所关心的,分享如何实现这个工作的例子吗?大多数我见过的例子,假设你呈现在服务器端的形式,然后将其发送(连同嵌入式csrf_token表单域)的客户端。在我的应用程序,所有的内容呈现在客户端通过Backbone.js的(包括模板)。所有的服务器确实是JSON格式,这是通过在客户端的Backbone.js的各种型号使用提供值。按照我的理解,我需要首先检索通过ajax的csrf_token它才能使用。不过,我很担心这可能是从安全角度来看问题。这是一个有效的关注?

Does anyone have a working example they care to share on how to implement this? Most of the examples I have seen, assume you are rendering the form on the server-side and then sending it (along with the embedded csrf_token form field) to the client-side. In my app, all content is rendered on the client-side (including templates) via Backbone.js. All the server does is provide values in JSON format, which are utilized by various Models in Backbone.js on the client-side. By my understanding I would need to retrieve the csrf_token via ajax first before it can be used. However, I am concerned this may be problematic from a security standpoint. Is this a valid concern?

推荐答案

它可以通过添加标记CSRF令牌来完成,然后通过CSRF令牌与每一个Ajax请求

It can be done by adding meta tag for CSRF token and then pass CSRF token with every Ajax request

添加CSRF中间件

app.use(express.csrf());
app.use(function (req, res, next) {
  res.locals.token = req.session._csrf;
  next();
});

您可以通过,比如通过一个CSRF标记到客户端,meta标签。对于离,在

You can pass a CSRF token to the client side via, say, a meta tag. For ex, in Jade

meta(name="csrf-token", content="#{token}")

客户端

jQuery有一个名为AJAX prefilter功能,它可以让你提供给被调用每一个Ajax请求的回调。然后用ajax prefilter设置一个头。

Client

jQuery has a feature called ajaxPrefilter, which lets you provide a callback to be invoked every Ajax request. Then set a header using ajaxPrefilter.

var CSRF_HEADER = 'X-CSRF-Token';

var setCSRFToken = function (securityToken) {
  jQuery.ajaxPrefilter(function (options, _, xhr) {
    if (!xhr.crossDomain) {
      xhr.setRequestHeader(CSRF_HEADER, securityToken);
    }
  });
};

setCSRFToken($('meta[name="csrf-token"]').attr('content'));

这篇关于如何调用使用EX press.js实现在阿贾克斯CSRF保护(寻求完整的例子)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆