如何用CSRF测试快递表格? [英] How to test express form post with CSRF?

查看:117
本文介绍了如何用CSRF测试快递表格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我的服务器端窗体验证写一个测试,但是我不断得到一个Forbidden错误。似乎这需要一个两步的过程。步骤1,从表单获取CSRF值。步骤2,使用CSRF值发布到表单处理程序。然而,无论我如何尝试发布我得到一个禁止的错误。

I'm trying to write a test for my server side form validation but I keep getting a Forbidden error. It seems that this needs to be a 2 step process. Step 1, acquire the CSRF value from the form. Step 2, use the CSRF value to post to the form handler. However no matter how I try to post I get a forbidden error.

- 全面测试: https://github.com/socketwiz/swblog/blob/master/test/contact.js#L57-L100

我尝试更改以下行:
https://github.com/socketwiz/swblog/blob/master/test/contact.js#L85

.send({name: 'foo', 'X-CSRF-Token': token})

.set('X-CSRF-Token', token)

.set('Cookie', ['X-CSRF-Token=' + token])

但是没有什么我会试图满足CSRF要求。越多,我尝试越复杂,这似乎是一件简单的事情。也许我会这么做错了。任何想法?

But nothing I try will seem to satisfy the CSRF requirement. The more I try the more complex this gets for what seems like a simple thing. Maybe I'm going about this all wrong. Any ideas?

推荐答案

感谢@shawnzhu,你对cookies的评论帮助我弄清楚我需要做什么。我有一个想法,我正在使它复杂化。这是我想出的:

Thanks @shawnzhu, you comment on cookies helped me figure out what I needed to do. I had an idea that I was over complicating it. Here is what I came up with:

https://github.com/socketwiz/swblog/blob/master/test/contact.js

it('should not post just a name', function(done) {
    request(mock)
      .get('/contact')
      .end(function(err, res){
        var $html = jQuery(res.text);
        var csrf = $html.find('input[name=_csrf]').val();

        request(mock)
          .post('/api/contact.json')
          .set('cookie', res.headers['set-cookie'])
          .send({
            _csrf: csrf,
            name: 'Mary Jane'
          })
          .expect(function(res){
            assert.equal(undefined, res.body.name);
            assert.equal('You must provide a valid email address', res.body.email);
            assert.equal('You must provide a message', res.body.message);
          })
          .expect(500, done);
      });
});

这篇关于如何用CSRF测试快递表格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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