使用csrf测试post方法

时间:2014-09-25 10:04:22

标签: go csrf-protection revel

我正在尝试编写一个测试方法,用于在我的revel应用程序上注册。请查看以下代码

package tests

import "github.com/revel/revel"
import "github.com/PuerkitoBio/goquery"
import "bytes"
import "net/url"

//import "net/http"

var csrf string

type AccountTest struct {
    revel.TestSuite
}

func (self *AccountTest) Before() {
    //println("Set up")
}

func (self *AccountTest) TestGetSignUp() {
    self.Get("/signup")
    site := bytes.NewBuffer(self.ResponseBody)
    doc, _ := goquery.NewDocumentFromReader(site)
    doc.Find("input").Each(func(i int, s *goquery.Selection) {
        name, exists := s.Attr("name")
        if name == "csrf_token" && exists {
            csrf, _ = s.Attr("value")
        }
    })
    self.AssertOk()
    self.AssertContains("Sign Up")
    self.AssertContentType("text/html; charset=utf-8")
}

func (self *AccountTest) TestPostSignUp() {
    self.PostForm("/signup", url.Values{
        "name":         {"cormier"},
        "email":        {"cormisample.com"},
        "emailConfirm": {"cormier@sample.com"},
        "password":     {"Test!1234"},
        "termof":       {"true"},
        "csrf_token":   {csrf},
    })
    self.AssertOk()
    self.AssertContentType("text/html; charset=utf-8")
}

func (self *AccountTest) After() {
    //println("Tear down")
} 

测试没有通过TestPostSignUp函数,似乎通过我实现的revel-csrf的csrf中间件拒绝了请求。如您所见,我读取了csrf令牌并保存到变量(csrf)中。通过Postform请求我传递了变量,但是不起作用。

我的问题是,如何使用将传递csrf保护的post请求进行测试。

1 个答案:

答案 0 :(得分:5)

我解决了以下问题:

package tests

    import "github.com/revel/revel"
    import "github.com/PuerkitoBio/goquery"
    import "bytes"
    import "net/url"

    //import "net/http"

    var csrf string

    type AccountTest struct {
        revel.TestSuite
    }

    func (self *AccountTest) Before() {

        self.Get("/signup")
        site := bytes.NewBuffer(self.ResponseBody)
        doc, _ := goquery.NewDocumentFromReader(site)
        doc.Find("input").Each(func(i int, s *goquery.Selection) {
            name, exists := s.Attr("name")
            if name == "csrf_token" && exists {
                csrf, _ = s.Attr("value")
            }
        })

    }

    func (self *AccountTest) TestSignUp() {

        self.PostForm("/signup", url.Values{
            "name":         {"cormier"},
            "email":        {"cormier@sample.com"},
            "emailConfirm": {"cormier@sample.com"},
            "password":     {"Test!1234"},
            "termof":       {"true"},
            "csrf_token":   {csrf},
        })
        self.AssertOk()
        self.AssertContentType("text/html; charset=utf-8")
    }

    func (self *AccountTest) After() {
    }